GATE / CS ARCHIVE

SUBJECT COLLECTION

Database Management Systems · SQL & Queries

47 questions, newest first

GATE CSE has asked 47 questions on SQL & Queries (Database Management Systems) from 1991 to 2025, in 33 of the 46 papers; the most recent is in GATE CSE 2025 Set 2. In the last five years it carried 1 marks per 100-mark paper on average, against 1.4 since 2003. Since 2014 the questions have been 9 MCQ, 8 NAT and 1 MSQ. 4 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · NAT
Report issue

Evaluating an SQL subquery and MIN aggregate

SQL & Queries

Question 55, GATE 2025: Tables: player(pid,pname,age) has (1,Jasprit,31),(2,Atharva,24),(3,Ishan,26),(4,Axar,30). coach(cid,cname) has (101,Ricky),(102,Mark),(103,Trevor). team(tid,tname,city,cid) has (10,MI,Mumbai,102),(20,DC,Delhi,101),(30,PK,Mohali,103). members(pid,tid) has (1,10),(2,30),(3,10),(4,20). Evaluate SELECT MIN(P.age) FROM player P WHERE P.pid IN (SELECT M.pid FROM team T,coach C,members M WHERE C.cname='Mark' AND T.cid=C.cid AND M.tid=T.tid).
Tap to enlarge
Answer & solution

Official answer: 26

Approach: Evaluate the inner join and filter to get a set of player IDs, then apply the outer aggregate only to those players.
The condition C.cname='Mark' selects coach row cid=102. Joining on T.cid=C.cid selects team tid=10, because that is the team coached by 102. Joining membership on M.tid=T.tid then selects the rows (1,10) and (3,10), so the subquery returns player IDs {1,3}.
The outer WHERE P.pid IN (...) retains Jasprit, age 31, and Ishan, age 26. MIN over those two ages is 26, which is the returned value.
Atharva’s age 24 is smaller overall but belongs to team 30 coached by Trevor; the predicate removes that row before MIN is computed. Axar likewise belongs to team 20 coached by Ricky. This demonstrates why aggregating over the entire player table before applying the team/coach restriction would be incorrect.

Original paper, page 55 · Answer key

2 marks · MSQ
Report issue

SQL & Queries

Question 54, GATE 2025: Schema: Students(rollno,name,age,cgpa), Courses(courseno,cname,credits), Enrolled(rollno,courseno,grade). Primary keys are Students.rollno, Courses.courseno, and the composite Enrolled(rollno,courseno). Which SQL queries retrieve names of students enrolled in course 1470?
A. SELECT S.name FROM Students S WHERE EXISTS (SELECT * FROM Enrolled E WHERE E.courseno=1470 AND E.rollno=S.rollno);
B. SELECT S.name FROM Students S WHERE SIZEOF (SELECT * FROM Enrolled E WHERE E.courseno=1470 AND E.rollno=S.rollno)>0;
C. SELECT S.name FROM Students S WHERE 0 < (SELECT COUNT(*) FROM Enrolled E WHERE E.courseno=1470 AND E.rollno=S.rollno);
D. SELECT S.name FROM Students S NATURAL JOIN Enrolled E WHERE E.courseno=1470;
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, C, D

A's correlated subquery considers enrollment rows for the current student's rollno and the requested course. EXISTS is true exactly when at least one such row exists, so A returns the desired name.

C tests the same correlated set. COUNT(*) returns a scalar count, including zero when no enrollment matches. The condition 0<count is therefore equivalent to existence, so C is also valid. B tries to use SIZEOF(subquery), which is not the standard SQL operator for counting a query result; COUNT(*) is the relevant aggregate.

For D, the only shared attribute name between Students and Enrolled is rollno, so NATURAL JOIN equates those roll numbers. Filtering the joined row by courseno=1470 selects enrolled students and projecting S.name gives their names. Thus D is the intended third valid query; Courses is unnecessary because the required course number is already stored in Enrolled.

The source marks (rollno,courseno) as Enrolled's composite primary key, so at most one enrollment can match a given student and course. D therefore has the same per-student-row multiplicity as A/C. Different students may share a name, and none of these queries removes such duplicate names. Without the composite-key constraint, a join could repeat a name per matching enrollment, but that is not the stated schema. The correct selection is A,C,D.

Original paper, page 42 · Answer key

2 marks · NAT
Report issue

SQL & Queries

Question 61, GATE 2023: Student rows (rollNum,name,gender,marks) are (1,Naman,M,62),(2,Aliya,F,70),(3,Aliya,F,80),(4,James,M,82),(5,Swati,F,65); rollNum is primary key. How many rows does SELECT * FROM Student WHERE gender='F' AND marks>65 return?
Tap to enlarge
Answer & solution

Official answer: 2

The condition requires both female gender and marks strictly greater than 65. Roll numbers 2 and 3 qualify, with marks 70 and 80. Swati has exactly 65 and is excluded; the other two rows are male. The two Aliya rows remain distinct because their roll numbers differ, and SELECT * does not deduplicate them. The result contains 2 rows.

Teaching detail. Evaluate the conjunction row by row: row 1 fails gender, row 2 passes both predicates, row 3 passes both, row 4 fails gender despite high marks, and row 5 fails the strict greater-than test. The primary key identifies records by rollNum, not by name, so equal names do not imply one record. SQL's ordinary SELECT is not SELECT DISTINCT; moreover even DISTINCT over all columns would keep the two qualifying rows because both roll numbers and marks differ. Only the number of qualifying rows is requested.

Original paper, page 64 · Answer key

2 marks · NAT
Report issue

SQL & Queries

Question 56, GATE 2022: Student(sNo,sName,dNo): (S01,James,D01),(S02,Rocky,D01),(S03,Jackson,D02),(S04,Jane,D01),(S05,Milli,D02). Dept: (D01,CSE),(D02,EEE). Course(cNo,cName,dNo): (C11,DS,D01),(C12,OS,D01),(C21,DE,D02),(C22,PT,D02),(C23,CV,D03). Register pairs: S01:C11,C12; S02:C11; S03:C21,C22,C23; S04:C11,C12; S05:C11,C21. Count rows returned by SELECT * FROM Student AS S WHERE NOT EXIST (SELECT cNo FROM Course WHERE dNo = “D01” EXCEPT SELECT cNo FROM Register WHERE sNo = S.sNo). The printed spelling/quotes are retained to expose the source syntax issue.
Tap to enlarge
Answer & solution

Official answer: 2

The intended NOT EXISTS test succeeds when the set of D01 courses minus the student's registered courses is empty. The D01 course set is {C11, C12}. Therefore the intended query returns 2 student rows. Source syntax discrepancy: the printed SQL says NOT EXIST, missing the final S, and uses typographic double quotes around D01. Executable standard SQL needs NOT EXISTS and a single-quoted character literal. The official numeric answer assumes these obvious syntax repairs; the literal printed statement is not valid standard SQL.

The missing-D01-course sets are S01:∅, S02:{C12}, S03:{C11,C12}, S04:∅, S05:{C12}. NOT EXISTS accepts only empty sets. A student’s own department is not a filter in the outer query; only coverage of the D01 courses matters.

Original paper, page 38 · Answer key

2 marks · MCQ
Report issue

SQL & Queries

Question 31, GATE 2021: Schema emp(empId,name,gender,salary,deptId), key empId, each employee in one department. Query: select deptId,count(*) from emp where gender="female" and salary>(select avg(salary) from emp) group by deptId. Counts female employees above which mean? A employees in department; B employees in company; C women in department; D women in company.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

The uncorrelated subquery averages salary across the entire emp relation, with no gender or department filter. The outer query counts female employees above that company-wide average, grouped by department. Thus B. Departments with no qualifying rows are omitted rather than returned with count 0. The printed double-quoted female is understood as an intended string literal; standard SQL uses single quotes, while double quotes ordinarily delimit identifiers.

The inner SELECT has no reference to the outer row, so its scalar mean is computed over all emp rows. The gender test is outside it and does not restrict that mean. GROUP BY affects the final count, not the subquery's population. This distinction separates all four options.

Original paper, page 72 · Answer key

1 mark · MCQ
Report issue

SQL & Queries

Question 13, GATE 2020: Catalogue(sno,pno,cost) has rows (S1,P1,150),(S1,P2,50),(S1,P3,100),(S2,P4,200),(S2,P5,250),(S3,P1,250),(S3,P2,150),(S3,P5,300),(S3,P4,250), primary key (sno,pno). Suppliers has primary key sno and one row each: S1/Royal furniture/Delhi, S2/Balaji furniture/Bangalore, S3/Premium furniture/Chennai. Parts has primary key pno: P1/Table/Wood, P2/Chair/Wood, P3/Table/Steel, P4/Almirah/Steel, P5/Almirah/Wood. Count rows returned by:
SELECT s.sno, s.sname FROM Suppliers s, Catalogue c
WHERE s.sno=c.sno AND cost >
(SELECT AVG(cost) FROM Catalogue WHERE pno='P4' GROUP BY pno);
Options: A 4; B 5; C 0; D 2.
Question 13, GATE 2020: Catalogue(sno,pno,cost) has rows (S1,P1,150),(S1,P2,50),(S1,P3,100),(S2,P4,200),(S2,P5,250),(S3,P1,250),(S3,P2,150),(S3,P5,300),(S3,P4,250), primary key (sno,pno). Suppliers has primary key sno and one row each: S1/Royal furniture/Delhi, S2/Balaji furniture/Bangalore, S3/Premium furniture/Chennai. Parts has primary key pno: P1/Table/Wood, P2/Chair/Wood, P3/Table/Steel, P4/Almirah/Steel, P5/Almirah/Wood. Count rows returned by:
SELECT s.sno, s.sname FROM Suppliers s, Catalogue c
WHERE s.sno=c.sno AND cost >
(SELECT AVG(cost) FROM Catalogue WHERE pno='P4' GROUP BY pno);
Options: A 4; B 5; C 0; D 2.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Worked explanation

Evaluate the uncorrelated scalar subquery once. Filtering pno=P4 leaves prices 200 and 250, so its one group has average 225. Apply the outer strict comparison to every Catalogue row; prices 250,250,300,250 survive. The supplier primary key makes each surviving row join with exactly one supplier row, so the join neither loses nor multiplies them. Projection returns S2 once and S3 three times. SQL SELECT uses bag semantics unless DISTINCT is requested; it does not automatically collapse those repeated S3 names. The Parts table is not referenced by this query and cannot affect the count.

Derivation and answer

The P4 rows have costs 200 and 250, so the subquery returns 225. Catalogue costs greater than 225 occur at(S2, P5),(S3, P1),(S3, P5),(S3, P4): four rows. The supplier join preserves all four and SELECT has no DISTINCT, so repeated S3 output rows remain. Answer 4, A.

Original paper, page 7 · Answer key

2 marks · NAT
Report issue

A Cartesian product before SQL grouping

SQL & Queries

Question 51, GATE 2019: Student rows (Roll_no,Student_name) are (1,Amit),(2,Priya),(3,Vinit),(4,Rohan),(5,Smita). Performance rows (Roll_no,Subject_code,Marks) are (1,A,86),(1,B,95),(1,C,90),(2,A,89),(2,C,92),(3,C,80). Student key is Roll_no and Performance key is (Roll_no,Subject_code). Query: SELECT S.Student_name, sum(P.Marks) FROM Student S, Performance P WHERE P.Marks>84 GROUP BY S.Student_name. How many rows result?
Tap to enlarge
Answer & solution

Official answer: 5

1. Read the actual WHERE clause before inferring the intended relationship. It contains P.Marks>84 but no condition S.Roll_no=P.Roll_no. Listing both tables in FROM therefore forms their Cartesian product, not a join on the similarly named columns.
2. Five Performance rows pass the filter: marks 86,95,90,89,92. The 80-mark row is excluded. Each of the five Student rows pairs with every one of these five surviving rows, yielding 25 intermediate rows.
3. GROUP BY S.Student_name partitions those rows by the five distinct student names. Each group has five rows and the same marks sum: 86+95+90+89+92=452.
4. The result is (Amit,452), (Priya,452), (Vinit,452), (Rohan,452), (Smita,452), in unspecified order. Hence the requested row count is 5.
5. Rohan and Smita are included even though they have no Performance records: the query never correlates a performance with its owner. Primary keys do not automatically add a join predicate. Adding that missing predicate would answer a different query and must not be silently done.

Original paper, page 15 · Answer key

1 mark · MCQ
Report issue

Superset among SQL joins

SQL & Queries

Question 12, GATE 2018: For Book(isbn,bname) and Stock(isbn,copies), all queries select B.isbn,S.copies and join on equal isbn. Queries 1–4 respectively use INNER, LEFT OUTER, RIGHT OUTER and FULL OUTER JOIN. Which result necessarily contains the other three? A 1; B 2; C 3; D 4.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Method

Divide possible output rows into matched pairs, unmatched Book rows and unmatched Stock rows. An inner join emits only the first group. A left join additionally emits unmatched Book rows with null Stock columns; a right join analogously preserves unmatched Stock rows. A full join includes all three groups. Even after the common projection, every row generated by a narrower join still occurs in the full join, with at least the same multiplicity.

Solution

The full outer join includes every matched pair plus all unmatched rows from each side padded by nulls. The inner and either one-sided outer join produce subsets of those rows after the same projection. Thus Query4, D; this remains a superset under SQL bag multiplicities.

Original paper, page 7 · Answer key

1 mark · NAT
Report issue

SQL & Queries

Question 23, GATE 2017: EMP(EmpId,EmpName,DeptName) has rows with IDs 1 through 13, names XYA through XYM, and departments AA,AA,AA,AA,AB,AB,AB,AC,AC,AC,AD,AD,AE respectively. The source SQL is:
SELECT AVG(EC.Num) FROM EC WHERE (DeptName, Num) IN
(SELECT DeptName, COUNT(EmpId) AS EC(DeptName, Num) FROM EMP GROUP BY DeptName)
Find its output. This unusual source syntax is retained; the solution distinguishes the intended aggregate from the literal SQL.
Tap to enlarge
Answer & solution

Official answer: 2.6

Our answer: 2.6 under intended grouped-table query

1. For the intended group operation, collect all rows with equal DeptName. The counts are AA:4, AB:3, AC:3, AD:2, AE:1.

2. AVG must average these five group counts, not average EmpId values or take an ungrouped COUNT. Their sum is 13, so the average is 13/5=2.6.

3. That derives the official intended numeric answer, but not an execution of the literal SQL. EC is not introduced as a proper relation/CTE, and AS EC(DeptName,Num) is not a valid ordinary COUNT alias. A corrected query must define EC before SELECT AVG(Num) FROM EC.

Original paper, page 12 · Answer key

2 marks · NAT
Report issue

SQL & Queries

Question 46, GATE 2017: top_scorer(player,country,goals) rows: Klose,Germany,16; Ronaldo,Brazil,15; G Müller,Germany,14; Fontaine,France,13; Pelé,Brazil,12; Klinsmann,Germany,11; Kocsis,Hungary,11; Batistuta,Argentina,10; Cubillas,Peru,10; Lato,Poland,10; Lineker,England,10; T Müller,Germany,10; Rahn,Germany,10. Query: SELECT ta.player FROM top_scorer AS ta WHERE ta.goals > ALL (SELECT tb.goals FROM top_scorer AS tb WHERE tb.country='Spain') AND ta.goals > ANY (SELECT tc.goals FROM top_scorer AS tc WHERE tc.country='Germany'). How many tuples result?
Tap to enlarge
Answer & solution

Official answer: 7.0

Our answer: 7

1. The Spain subquery returns no rows. A comparison quantified by ALL over an empty set is true, because there is no counterexample. Hence the first predicate eliminates none of the outer rows.

2. The Germany subquery returns goals 16,14,11,10,10. The >ANY condition requires exceeding at least one of them, so with these non-NULL values it is equivalent to goals>10, not goals>16.

3. Seven rows have goal counts above 10: 16,15,14,13,12,11,11. They yield Klose,Ronaldo,G Müller,Fontaine,Pelé,Klinsmann,Kocsis, so the result has 7 tuples. The query does not say DISTINCT, but these seven selected player values are distinct anyway. Empty ALL and empty ANY behave differently.

Original paper, page 19 · Answer key

2 marks · NAT
Report issue

SQL & Queries

Question 52, GATE 2016: water_schemes(scheme_no,district_name,capacity) rows: (1,Ajmer,20),(1,Bikaner,10),(2,Bikaner,10),(3,Bikaner,20),(1,Churu,10),(2,Churu,20),(1,Dungargarh,10). Printed pseudocode: with total(name,capacity) as select district_name,sum(capacity) from water_schemes group by district_name; with total_avg(capacity) as select avg(capacity) from total; select name from total,total_avg where total.capacity≥total_avg.capacity. How many output tuples under the intended CTE interpretation? The printed text repeats WITH and omits required CTE parentheses.
Tap to enlarge
Answer & solution

Official answer: 2.0 : 2.0

Our answer: 2 under intended corrected CTE syntax

Per-district totals are Ajmer20, Bikaner40, Churu30, Dungargarh10; their mean is 25. Bikaner and Churu meet the >=25 condition, so the intended result has 2 tuples. Literal standard SQL requires parenthesized CTE bodies and a comma separating total and total_avg under one WITH clause. The printed repeated WITH and missing parentheses are not executable standard CTE syntax; the official 2 assumes those syntax repairs.

GROUP BY first produces one row per district, so AVG operates over four totals, not the seven original scheme rows. The single average row is crossed with those four totals; filtering retains 40 and 30. A repaired standard SQL form uses WITH total AS (...), total_avg AS (...) SELECT ..., making the intended semantics executable without claiming the printed syntax is valid.

Original paper, page 42 · Answer key

1 mark · MCQ
Report issue

SQL & Queries

Question 31, GATE 2015: The SELECT operation in SQL corresponds to which relational-algebra operation? A selection; B selection but retaining duplicates; C projection; D projection but retaining duplicates.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Projection chooses output columns, whereas relational selection filters rows. A SQL SELECT list chooses the displayed columns, and ordinary SELECT uses bag semantics: two identical projected rows can both remain. Classical relational projection eliminates duplicates because a relation is a set. SELECT DISTINCT supplies the duplicate-eliminating counterpart. A full SQL query may additionally perform filtering, grouping and joins.

Solution: The SQL SELECT list performs projection, but without DISTINCT it retains duplicate result rows. Thus it corresponds to relational projection with duplicate retention, D; this describes the list operation, not every clause of a full query.

Original paper, page 12 · Answer key

2 marks · NAT
Report issue

SQL & Queries

Question 61, GATE 2015: Student(Roll_No,Student_Name) rows: (1,Raj),(2,Rohit),(3,Raj). Performance(Roll_No,Course,Marks): (1,Math,80),(1,English,70),(2,Math,75),(3,English,80),(2,Physics,65),(3,Math,80). SQL: SELECT S.Student_Name,sum(P.Marks) FROM Student S,Performance P WHERE S.Roll_No=P.Roll_No GROUP BY S.Student_Name. How many output rows?
Tap to enlarge
Answer & solution

Official answer: 2

The equality join associates each course result with the appropriate student record, producing six joined rows. GROUP BY uses the name column, not the unique roll number, so the two Raj students become one aggregate group. The result contains (Raj,310) and (Rohit,140). Counting students gives three and counting course records gives six, but neither is the number of distinct grouping keys.

Solution: The join matches each performance row to its student by Roll_No, but grouping is by Student_Name alone. Roll numbers 1 and 3 both have name Raj and collapse into one group with total 80+70+80+80=310. Rohit forms the other group with 75+65=140. Hence2 result rows.

Original paper, page 23 · Answer key

1 mark · MCQ
Report issue

SQL & Queries

Question 29, GATE 2015: For Cinema(theater,address,capacity), append a condition to SELECT P1.address FROM Cinema P1 so that it returns addresses of theaters having maximum capacity. Options: (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). Explain the ordinary nonnull-capacity assumption.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A for nonnull capacities

1. P1.capacity≥ALL capacities selects exactly maximal capacities, including ties, A.

2. ANY admits smaller nonmaximal values, and strictly greater than MAX admits none. This assumes capacities are nonnull: a NULL in the subquery can make ALL unknown even for a maximum; a NULL-safe implementation filters null capacities or compares to MAX.

Original paper, page 62 · Answer key

1 mark · MCQ
Report issue

SQL & Queries

Question 22, GATE 2014: S1: A foreign-key declaration can always be replaced by an equivalent SQL check assertion. S2: If R(a,b,c) has composite primary key (a,b), then CREATE TABLE S(a INTEGER,d INTEGER,e INTEGER,PRIMARY KEY(d),FOREIGN KEY(a) REFERENCES R) is valid. Choose A: S1 true, S2 false. B: both true. C: S1 false, S2 true. D: both false.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D with full referential-action semantics; A for constraints alone

1. Method and setup. Check S2 structurally: omitting referenced column names means referencing R’s primary key, which has two columns, unlike the one-column foreign key. For S1, distinguish an assertion describing permitted database states from actions performed during an update or deletion. “Always equivalent” is ambiguous unless that distinction is specified.

2. Work through the result and its assumptions. S2 is false: the implicit referenced key is composite(a, b), but the foreign key has only one column. For S1, an SQL ASSERTION can express the allowed-state condition for an ordinary foreign key, including NULL exemptions, so under constraint-only equivalence S1 is true and A follows. An assertion alone cannot implement ON DELETE/UPDATE CASCADE or SET NULL actions; interpreting always as full behavioral equivalence makes S1 false and supports official D. This distinction is unstated; retain the official key and disclose both readings.

Original paper, page 12 · Answer key

2 marks · MCQ
Report issue

SQL & Queries

Question 54, GATE 2014: Schemas: employees(emp-id,first-name,last-name,hire-date,dept-id,salary) and departments(dept-id,dept-name,manager-id,location-id). To list last names and hire dates of all latest hires in each department at location 1700, the printed query is SELECT last-name,hire-date FROM employees WHERE (dept-id,hire-date) IN (SELECT dept-id,MAX(hire-date) FROM employees JOIN departments USING(dept-id) WHERE location-id=1700 GROUP BY dept-id). Outcome? A: Executes but incorrect. B: Executes and correct. C: Error because of pairwise comparison. D: Error because GROUP BY cannot accompany joins in a subquery. Hyphens are printed unquoted.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Our answer: B after identifier syntax repair

1. Method and setup. Read the subquery from its FROM clause onward: join employees to departments, restrict the departments by location, and group to obtain each department’s latest date. The outer predicate must match both department and date, preventing a latest date from one department accidentally selecting a person in another. Separately audit the literal identifier syntax.

2. Work through the result and its assumptions. Treating the hyphenated labels as properly quoted identifiers (or replacing hyphens with underscores), the inner query groups employees by department at location 1700 and returns each latest hire date. The outer row-value IN comparison selects all employees tied at those dates in their departments. Thus the intended result is correct, B; GROUP BY with a join and pairwise IN are valid. Literally, unquoted dept-id, last-name and other hyphenated names are not ordinary SQL identifiers: subtraction is parsed or syntax fails, especially USING(dept-id). The printed query needs identifier quoting/renaming.

Original paper, page 21 · Answer key

2 marks · MCQ
Report issue

SQL & Queries

Question 54, GATE 2014: SQL relations may contain duplicate tuples. Which query always matches SELECT * FROM R WHERE a IN (SELECT S.a FROM S)? A SELECT R.* FROM R,S WHERE R.a=S.a; B SELECT DISTINCT R.* FROM R,S WHERE R.a=S.a; C SELECT R.* FROM R,(SELECT DISTINCT a FROM S) AS S1 WHERE R.a=S1.a; D SELECT R.* FROM R,S WHERE R.a=S.a AND is unique R.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. Set up the reasoning. IN is an existence test: a matching R occurrence survives once irrespective of how many matching S rows exist. Reproduce that effect by deduplicating only S's join-key values before joining.

2. Derive the result. IN tests membership, preserving each original occurrence of an R row once when at least one matching nonnull S.a exists. Joining to SELECT DISTINCT a FROM S creates exactly one matching S1 row per such value, preserving R’s multiplicities: C. A multiplies rows when S repeats a; B removes duplicate R rows. SQL null comparisons remain nontrue in both the IN filter and equality join, so nulls do not invalidate C.

3. Check the interpretation. A can multiply an R occurrence by duplicate S keys; B can erase distinct occurrences of the same R tuple. C keeps R's bag multiplicity while giving one matching right-side row. NULL does not satisfy either filter's equality test, so it does not break the equivalence.

Original paper, page 43 · Answer key

2 marks · MCQ
Report issue

SQL & Queries

Question 54, GATE 2014: Schemas are employee(empId,empName,empDept) and customer(custId,custName,salesRepId,rating), with salesRepId referencing empId. Every employee sells to at least one customer. Query: SELECT empName FROM employee E WHERE NOT EXISTS (SELECT custId FROM customer C WHERE C.salesRepId=E.empId AND C.rating <> 'GOOD'). It returns names of employees with A at least one GOOD customer; B at most one GOOD customer; C no GOOD customers; D all customers GOOD.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D assuming nonnull ratings

Step 1: For a fixed employee, the correlated subquery considers only that employee's customers, and finds rows whose rating is unequal to GOOD. NOT EXISTS keeps the employee exactly when this set is empty. Step 2: If ratings are non-NULL, having no customer rated other than GOOD means every customer is GOOD. The premise guarantees at least one customer, so the intended option is D. Step 3: The source does not declare rating NOT NULL. In SQL, NULL <> 'GOOD' is UNKNOWN, not TRUE, so a NULL-rated customer does not enter the subquery. An employee with only NULL-rated customers is still returned even though all-GOOD is not established. The precise query means “no own customer has a known non-GOOD rating”; retain the official D qualification and existing NULL discrepancy.

Original paper, page 66 · Answer key

1 mark · MCQ
Report issue

HAVING without GROUP BY and unselected grouping attributes

SQL & Queries

Question 15, GATE 2012: Which of the following statements are TRUE about an SQL query?

        P : An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause
        Q : An SQL query can contain a HAVING clause only if it has a GROUP BY clause
        R : All attributes used in the GROUP BY clause must appear in the SELECT clause
        S : Not all attributes used in the GROUP BY clause need to appear in the SELECT clause
        (A) P and R             (B) P and S              (C) Q and R             (D) Q and S
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: B

P is true: SELECT COUNT(*) FROM T HAVING COUNT(*)>0 is a valid aggregate query without GROUP BY, treating the input as one group. S is true: SELECT COUNT(*) FROM T GROUP BY a groups by a without selecting a. Therefore Q and R are false, and the correct pair is P and S, option B. The appended official Code A key instead prints C (Q and R). Preserve official C for scoring provenance and derived B as a documented source/key discrepancy; do not silently change either.

Check: On a table with values a=1,1,2, grouping by a while selecting only COUNT(*) returns counts 2 and 1 without exposing a. On the same nonempty table, HAVING COUNT(*)>0 without GROUP BY retains its one aggregate group. These concrete cases refute both universal claims Q and R.

Original paper, page 4 · Answer key

2 marks · MCQ
Report issue

ALL over an empty SQL subquery

SQL & Queries

Question 51, GATE 2012: Relations: A(Id,Name,Age)={(12,Arun,60),(15,Shreya,24),(99,Rohit,11)}; B(Id,Name,Age)={(15,Shreya,24),(25,Hari,40),(98,Rohit,20),(99,Rohit,11)}; C(Id,Phone,Area)={(10,2200,02),(99,2100,01)}.
How many tuples result from this SQL query?
SELECT A.Id FROM A WHERE A.Age > ALL (SELECT B.Age FROM B WHERE B.Name='Arun');
(A) 4 (B) 3 (C) 0 (D) 1.
Question 51, GATE 2012: Relations: A(Id,Name,Age)={(12,Arun,60),(15,Shreya,24),(99,Rohit,11)}; B(Id,Name,Age)={(15,Shreya,24),(25,Hari,40),(98,Rohit,20),(99,Rohit,11)}; C(Id,Phone,Area)={(10,2200,02),(99,2100,01)}.
How many tuples result from this SQL query?
SELECT A.Id FROM A WHERE A.Age > ALL (SELECT B.Age FROM B WHERE B.Name='Arun');
(A) 4 (B) 3 (C) 0 (D) 1.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

There is no B row with Name=Arun, so the inner query returns an empty relation. A comparison quantified by ALL over an empty set is true: there is no counterexample. Consequently all three rows of A satisfy the WHERE condition, returning Id values 12, 15, 99. The count is 3, B.

Check: ALL means every returned value satisfies the comparison, not that at least one value exists. NOT EXISTS a violating subquery row is true when there are no subquery rows at all. ANY would have the opposite empty-set truth value, false.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Generated SQL table recurrence

SQL & Queries

Question 32, GATE 2011: Table T has integer columns X,Y and starts with (1,1). Let MX and MY be their current respective maxima. Perform 128 additional inserts of (MX+1,2*MY+1), recomputing maxima after each insert. What does SELECT Y FROM T WHERE X=7 return?

(A) 127
(B) 255
(C) 129
(D) 257
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A under successful mathematical-integer insertions

The rows obey X=k and Y=2k−1 by induction from(1, 1): the next maximum Y is doubled and increased by 1. Hence the row X=7 has Y=127, A. Completing all 128 additional inserts would require representing 2129−1 in the final row, beyond common fixed-width SQL INTEGER types. The problem’s statement that all inserts occur therefore assumes sufficiently large integers or an abstract unbounded-integer model; the requested early row itself is representable.

The early rows make the indexing clear: (1,1),(2,3),(3,7),(4,15),(5,31),(6,63),(7,127). Since X increases strictly, there is exactly one row with X=7. For a formal recurrence, set Z=Y+1; then Z doubles at each step, with Z=2 initially, so at X=k it equals 2k. The query is not asking for the final maximum after all 128 inserts; that confusion produces inappropriate much larger powers.

Original paper, page 9 · Answer key

2 marks · MCQ
Report issue

Counting a natural join on a shared manager

SQL & Queries

Question 46, GATE 2011: Loan_Records has columns Borrower,Bank_Manager,Loan_Amount and rows (Ramesh,Sunderajan,10000.00), (Suresh,Ramgopal,5000.00), (Mahesh,Sunderajan,7000.00). Evaluate 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
(C) 5
(D) 6
Tap to enlarge
Your answer
Answer & solution

Official answer: C

The common column of the two projections is Bank_Manager. Sunderajan appears in two rows of each projection, so the natural join yields 2×2=4 combinations for that manager. Ramgopal appears once in each projection, yielding 1×1=1 combination. COUNT(*) returns 4+1=5, option C. The join does not pair rows by their original borrower, since Borrower is absent from the second projection.

The projected left rows are (Ramesh,Sunderajan),(Suresh,Ramgopal),(Mahesh,Sunderajan). The right rows are (Sunderajan,10000),(Ramgopal,5000),(Sunderajan,7000). Each of Ramesh and Mahesh joins with both Sunderajan amounts, yielding four rows; Suresh joins with the single Ramgopal amount. COUNT(*) counts those joined rows, including combinations that were not in the original table. Joining projections can create extra combinations whenever their common attribute is not a key.

Original paper, page 12 · Answer key

1 mark · MCQ
Report issue

Correlated SQL EXISTS filter

SQL & Queries

Question 19, GATE 2010: Schemas: Passenger(pid,pname,age) and Reservation(pid,class,tid).
Passenger rows: (0,Sachin,65), (1,Rahul,66), (2,Sourav,67), (3,Anil,69).
Reservation rows: (0,AC,8200), (1,AC,8201), (2,SC,8201), (5,AC,8203), (1,SC,8204), (3,AC,8202).
Which pids does this query return?
SELECT pid FROM Reservation
WHERE class='AC' AND EXISTS
 (SELECT * FROM Passenger WHERE age>65 AND Passenger.pid=Reservation.pid);
Options: (A) 1,0; (B) 1,2; (C) 1,3; (D) 1,5.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

The outer query first keeps AC reservation rows, whose passenger IDs are 0,1,5,3. The correlated EXISTS requires a Passenger row with the same pid and age greater than 65. ID 0 has age exactly 65 and fails; ID 5 has no Passenger row and fails. IDs 1 and 3 have ages 66 and 69 and pass, giving 1,3, option C.

EXISTS tests whether at least one matching subquery row exists; it does not require every Passenger row to meet the age condition. Passenger 2 is old enough but its only reservation is SC, so the outer AC filter removes it. Passenger 1’s additional SC reservation also does not add another output row. No ORDER BY is present, so 1,3 describes the result members rather than a guaranteed row order.

Original paper, page 4

2 marks · MCQ
Report issue

Nested NOT IN supplier query

SQL & Queries

Question 55, GATE 2009: Schema Suppliers(sid key, sname, city, street), Parts(pid key, pname, color), Catalog(sid, pid composite key, cost). Query SELECT S.sname FROM Suppliers S WHERE S.sid NOT IN(SELECT C.sid FROM Catalog C WHERE C.pid NOT IN(SELECT P.pid FROM Parts P WHERE P.color<>blue)). Relations nonempty. Options suppliers who A supplied a non-blue part; B have not supplied a non-blue part; C supplied only blue parts; D have not supplied only blue parts. Preserve SQL-null/referential-integrity and wording qualifications.
Question 55, GATE 2009: Schema Suppliers(sid key, sname, city, street), Parts(pid key, pname, color), Catalog(sid, pid composite key, cost). Query SELECT S.sname FROM Suppliers S WHERE S.sid NOT IN(SELECT C.sid FROM Catalog C WHERE C.pid NOT IN(SELECT P.pid FROM Parts P WHERE P.color<>blue)). Relations nonempty. Options suppliers who A supplied a non-blue part; B have not supplied a non-blue part; C supplied only blue parts; D have not supplied only blue parts. Preserve SQL-null/referential-integrity and wording qualifications.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

The innermost query finds non-blue part IDs. The middle query finds supplier IDs for catalog rows whose part is not in that set, i.e. suppliers of a blue part under the intended referential-integrity and non-NULL color assumptions. The outer NOT IN therefore returns names of suppliers who supply no blue parts, including suppliers with no catalog rows. The intended option is D, but its printed wording is imprecise: “have not supplied only blue parts” logically also includes mixed-color suppliers, whereas the SQL excludes them. A asks for any non-blue supply and also includes mixed suppliers; B and C concern suppliers with no non-blue supply / only blue supply, the opposite condition. Thus no option states the exact result under a literal reading. Do not present D as an officially verified or exact semantic equivalence.

Read the nested NOT IN clauses from inside out. First collect non-blue part IDs; next collect suppliers with a catalog part outside that set, meaning a blue part under non-null referential-integrity assumptions; finally exclude those suppliers. The result is suppliers with no blue supply, including suppliers with no catalog row. A supplier of both blue and red is excluded. That mixed-supply example demonstrates why printed D is not literally equivalent to the SQL despite being the intended choice. The discrepancy is semantic, not a reason to invent an official key.

Original paper, page 13

2 marks · MCQ
Report issue

Salary greater than every department employee

SQL & Queries

Question 61, GATE 2007: employee(empId,name,department,salary) has more than one employee in department 5. We want employees paid more than every department-5 employee. Compare:
Q1: SELECT e.empId FROM employee e WHERE NOT EXISTS (SELECT * 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");
Which statement is intended for an arbitrary table under non-NULL salary semantics?
Options:
(A) Q1 is correct
(B) Q2 is correct
(C) Both always produce the same answer
(D) Neither is correct
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Approach. NOT EXISTS rejects the presence of a counterexample to “greater than everyone.” SQL ANY is existential: satisfying one comparison suffices. DISTINCT does not change that quantifier.

2. Derivation and interpretation. For each e, Q1 excludes e whenever any department-5 employee has salary >= e.salary. Thus it keeps exactly salaries strictly greater than the department maximum. Q2 uses > ANY, which means greater than at least one returned salary, not every salary. For department salaries 10 and 20, a salary 15 passes Q2 but not Q1. Hence A under the usual non-NULL salary interpretation. Strict SQL NULL semantics require qualification: NULL comparisons are UNKNOWN, so Q1 can admit NULL salaries or ignore unknown department salaries; no NOT NULL constraint is printed.

Original paper, page 15

2 marks · MCQ
Report issue

Ranking balances with self-joins

SQL & Queries

Question 67, GATE 2006: Relation account(customer,balance) has customer as primary key and no nulls. Rank by decreasing balance, starting at 1, tying equal balances and skipping ranks (two tied maxima both rank 1, next rank 3).
Q1: SELECT A.customer,COUNT(B.customer) FROM account A,account B WHERE A.balance<=B.balance GROUP BY A.customer;
Q2: SELECT A.customer,1+COUNT(B.customer) FROM account A,account B WHERE A.balance<B.balance GROUP BY A.customer;
Statements: 1 Q1 and Q2 agree for some but not all databases; 2 both implement the rank specification; 3 Q1 is correct but Q2 is not; 4 neither is correct; 5 pure relational ranking is faster than scanning in decreasing balance order and assigning ranks through ODBC. Which pair is correct?
Options:
(A) 2 and 5
(B) 1 and 3
(C) 1 and 4
(D) 3 and 5
Question 67, GATE 2006: Relation account(customer,balance) has customer as primary key and no nulls. Rank by decreasing balance, starting at 1, tying equal balances and skipping ranks (two tied maxima both rank 1, next rank 3).
Q1: SELECT A.customer,COUNT(B.customer) FROM account A,account B WHERE A.balance<=B.balance GROUP BY A.customer;
Q2: SELECT A.customer,1+COUNT(B.customer) FROM account A,account B WHERE A.balance<B.balance GROUP BY A.customer;
Statements: 1 Q1 and Q2 agree for some but not all databases; 2 both implement the rank specification; 3 Q1 is correct but Q2 is not; 4 neither is correct; 5 pure relational ranking is faster than scanning in decreasing balance order and assigning ranks through ODBC. Which pair is correct?
Options:
(A) 2 and 5
(B) 1 and 3
(C) 1 and 4
(D) 3 and 5
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Query1 counts B rows with A.balance≤B.balance, so a customer tied with t customers at its balance receives the count of higher-balance customers plus t, instead of plus 1. For two tied maximum balances it gives 2, not 1.

2. Query2 uses A.balance<B.balance and adds 1 to the count, but its inner join produces no group for maximum-balance customers; those customers disappear. Thus neither query is correct (statement 4).

3. They agree on the empty database but differ on every nonempty database because Query1 includes the maximum group and Query2 does not, establishing statement 1 under the allowed empty-database case. Hence statements 1 and 4, option C.

4. Statement 5 is not a general performance guarantee.

5. Teaching check: The intended rank is 1 plus the number of strictly higher balances. Q1 instead counts all tied customers along with higher ones. Q2 uses the correct comparison but an inner join removes maxima, so adding one to its count does not restore the missing rows.

Original paper, page 10

2 marks · MCQ
Report issue

SQL duplicate semantics in membership queries

SQL & Queries

Question 68, GATE 2006: Schemas enrolled(student,course), key (student,course), and paid(student,amount), key student; no nulls, foreign keys or additional constraints.
Q1: SELECT student FROM enrolled WHERE student IN (SELECT student FROM paid);
Q2: SELECT student FROM paid WHERE student IN (SELECT student FROM enrolled);
Q3: SELECT E.student FROM enrolled E,paid P WHERE E.student=P.student;
Q4: SELECT student FROM paid WHERE EXISTS (SELECT * FROM enrolled WHERE enrolled.student=paid.student);
Which statement holds under SQL result-bag semantics (no DISTINCT)?
Options:
(A) All four return identical rows for every database
(B) Q2 and Q4 always agree, but Q1 and Q2 can differ
(C) Q3 can return strictly fewer rows than Q2
(D) Q4 can encounter a runtime integrity violation
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Query2 and Query4 each scan paid, whose student key is unique, and keep exactly students with an enrolled match. They therefore return identical bags with one row per matching student.

2. Query1 scans enrolled and returns one student occurrence for each matching enrollment; Query3 has the same multiplicities because paid has at most one matching row. A paid student enrolled in two courses appears twice in Query1/3 but once in Query2/4.

3. Thus B. SELECT alone does not eliminate duplicate rows; the phrase row sets must be interpreted as SQL result rows/bags.

4. Teaching check: A membership predicate filters each outer row but does not collapse duplicates already present in the outer projection. The paid key guarantees one outer row per student for Q2/Q4, whereas enrolled can contain several courses per student for Q1/Q3. Relational set intuition must not erase SQL multiplicities.

Original paper, page 10

2 marks · MCQ
Report issue

Correlated count of more expensive books

SQL & Queries

Question 77, GATE 2005: book(title, price) has distinct prices. Query SELECT title FROM book B WHERE (SELECT COUNT(*) FROM book T WHERE T.price>B.price)<5. A four most expensive titles; B fifth cheapest; C fifth most expensive; D five most expensive titles. Examine NULL prices separately.
Tap to enlarge
Your answer
Answer & solution

Answer: D, assuming non-NULL prices (no official key was published)

For each B the subquery counts books with a strictly higher price. The predicate count<5 selects ranks 1 through 5 in descending price order, because they have respectively 0 through 4 more expensive books. Distinct prices rule out ties. The result is the titles of the five most expensive books (or all books if fewer than five), option D. This intended interpretation additionally assumes prices are non-NULL. Distinct prices alone does not establish a NOT NULL constraint: for a row B with NULL price, every T.price>B.price comparison is UNKNOWN, so the subquery counts zero and that NULL-priced row is included regardless of the five highest non-NULL prices.

For a book with descending rank r and a non-NULL unique price, exactly r−1 rows are more expensive. The predicate r−1<5 is r≤5, yielding the top five, not merely the fifth. COUNT(*) counts qualifying rows, never the current book because comparison is strict. If B.price is NULL, every comparison is UNKNOWN and no row qualifies, so count is 0 and that book also passes. Distinctness alone must not be silently upgraded to NOT NULL.

Original paper, page 10

2 marks · MCQ
Report issue

Grouped salary comparison with global average

SQL & Queries

Question 53, GATE 2004: Employee(name,sex,salary,deptName) has key name. What department names does this SQL query return?
SELECT deptName FROM Employee
WHERE sex='M'
GROUP BY deptName
HAVING AVG(salary) > (SELECT AVG(salary) FROM Employee);
Options:
(A) Departments whose average salary exceeds the company average
(B) Departments whose male average salary exceeds the company-wide male average
(C) Departments whose male average salary exceeds the average of all employees in that department
(D) Departments whose male average salary exceeds the company average
Question 53, GATE 2004: Employee(name,sex,salary,deptName) has key name. What department names does this SQL query return?
SELECT deptName FROM Employee
WHERE sex='M'
GROUP BY deptName
HAVING AVG(salary) > (SELECT AVG(salary) FROM Employee);
Options:
(A) Departments whose average salary exceeds the company average
(B) Departments whose male average salary exceeds the company-wide male average
(C) Departments whose male average salary exceeds the average of all employees in that department
(D) Departments whose male average salary exceeds the company average
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. WHERE sex=M filters the outer rows to male employees before grouping by department. HAVING compares each such group’s average salary with the uncorrelated subquery SELECT AVG(salary) FROM Employee, which averages all employees company-wide.

2. Therefore it returns departments whose male employees’ average exceeds the overall company average. The inner query has no male filter and is not restricted to the same department.

3. Teaching check: Read SQL in stages: WHERE keeps only males; GROUP BY makes one male group per department; HAVING compares its average against a separately computed company-wide average. There is no correlation predicate linking the subquery to the department, and no sex filter inside it.

Original paper, page 7

2 marks · MCQ
Report issue

Existential selection in a three-relation join

SQL & Queries

Question 86, GATE 2003: Relations are Students(Roll_number,Name,Date_of_birth), Courses(Course_number,Course_name,Instructor), and Grades(Roll_number,Course_number,Grade). Interpret this query with the printed string constants rendered in SQL quotes:
SELECT DISTINCT Name
FROM Students,Courses,Grades
WHERE Students.Roll_number=Grades.Roll_number
  AND Courses.Instructor='Korth'
  AND Courses.Course_number=Grades.Course_number
  AND Grades.Grade='A';
What set is computed?
A. Students' names with A in all courses taught by Korth
B. Students' names with A in all courses
C. Students' names with A in at least one course taught by Korth
D. None of the above
Question 86, GATE 2003: Relations are Students(Roll_number,Name,Date_of_birth), Courses(Course_number,Course_name,Instructor), and Grades(Roll_number,Course_number,Grade). Interpret this query with the printed string constants rendered in SQL quotes:
SELECT DISTINCT Name
FROM Students,Courses,Grades
WHERE Students.Roll_number=Grades.Roll_number
  AND Courses.Instructor='Korth'
  AND Courses.Course_number=Grades.Course_number
  AND Grades.Grade='A';
What set is computed?
A. Students' names with A in all courses taught by Korth
B. Students' names with A in all courses
C. Students' names with A in at least one course taught by Korth
D. None of the above
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The Roll_number equality pairs each student with that student's grade records. The Course_number equality pairs each grade with its course.
2. The two filters discard any joined row whose instructor is not Korth or whose grade is not A. Every surviving row therefore witnesses one qualifying course for that student.
3. Projection selects the name and DISTINCT removes repeated names when several qualifying rows exist. It does not test unselected rows or require every course to qualify.
4. Thus a student appears if at least one qualifying Korth-course A exists, C. Requiring all such courses would need a different universal/anti-existence/division construction.

Solution: The joins connect each student to their grade records and the corresponding courses. The filters retain records having grade A in a course taught by Korth. A student's name is produced whenever at least one such joined record exists, and DISTINCT removes duplicate names. There is no universal quantifier, division, or count comparison requiring all courses to qualify. The intended relational query therefore computes option C, names of students with an A in at least one course taught by Korth.

Original paper, page 12

Descriptive
Report issue

Degree programs with offers to over five students

SQL & Queries

Question 15(b), GATE 2002: Placement schema COMPANY(cname,clocation), STUDENT(srollno,sname,sdegree), INTERVIEW(cname,srollno,idate), OFFER(cname,srollno,osalary). Keys: cname; srollno; (cname,srollno) for each remaining relation. cname and clocation are company name and location; srollno, sname and sdegree are student roll number, name and degree program. Interviews record company/student/date; offers record salary for successful interviews. Original15(b): Write SQL listing each degree program with more than five students offered jobs, together with the program name and average offered salary of its students.
Question 15(b), GATE 2002: Placement schema COMPANY(cname,clocation), STUDENT(srollno,sname,sdegree), INTERVIEW(cname,srollno,idate), OFFER(cname,srollno,osalary). Keys: cname; srollno; (cname,srollno) for each remaining relation. cname and clocation are company name and location; srollno, sname and sdegree are student roll number, name and degree program. Interviews record company/student/date; offers record salary for successful interviews. Original15(b): Write SQL listing each degree program with more than five students offered jobs, together with the program name and average offered salary of its students.
Question 15(b), GATE 2002: Placement schema COMPANY(cname,clocation), STUDENT(srollno,sname,sdegree), INTERVIEW(cname,srollno,idate), OFFER(cname,srollno,osalary). Keys: cname; srollno; (cname,srollno) for each remaining relation. cname and clocation are company name and location; srollno, sname and sdegree are student roll number, name and degree program. Interviews record company/student/date; offers record salary for successful interviews. Original15(b): Write SQL listing each degree program with more than five students offered jobs, together with the program name and average offered salary of its students.
Tap to enlarge
Answer & solution

Answer: SELECT S.sdegree, AVG(O.osalary) AS avg_offered_salary FROM STUDENT S JOIN OFFER O ON O.srollno=S.srollno GROUP BY S.sdegree HAVING COUNT(DISTINCT S.srollno)>5; (no official key was published)

A query under the usual interpretation of average offered salary, averaging the offer records, is:
SELECT S.sdegree, AVG(O.osalary) AS avg_offered_salary
FROM STUDENT AS S JOIN OFFER AS O ON O.srollno=S.srollno
GROUP BY S.sdegree
HAVING COUNT(DISTINCT S.srollno)>5;
The join associates each offer with its student's degree. COUNT(DISTINCT S.srollno) implements more than five students, not more than five offers: the composite OFFER key permits several companies to offer jobs to one student. AVG(O.osalary) averages the offered salary values within the degree group. No JOIN to INTERVIEW is needed, because OFFER already identifies successful candidates.

Original paper, page 8

Report issue

Self-join view before insertion

SQL & Queries

Question 17(b)(i), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(i): Find the current contents of V.
Question 17(b)(i), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(i): Find the current contents of V.
Question 17(b)(i), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(i): Find the current contents of V.
Tap to enlarge
Answer & solution

Answer: V={(1,3),(1,4),(2,5)}. (no official key was published)

The view combines a tuple (u,v) in the first copy of R with a tuple (v,w) in the second and returns (u,w), so it enumerates two-edge paths. For R={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}, the paths 1→2→3 and 1→2→4 yield (1,3),(1,4), while 2→4→5 yields (2,5). No other second component matches a first component. Thus V contains exactly those three tuples. They are distinct, so SQL bag semantics and set semantics give the same contents for this instance.

Original paper, page 9

Report issue

Incremental self-join view after two inserted tuples

SQL & Queries

Question 17(b)(ii), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(ii): Insert(2,11),(11,6) into R. Which additional tuples enter V?
Question 17(b)(ii), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(ii): Insert(2,11),(11,6) into R. Which additional tuples enter V?
Question 17(b)(ii), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(ii): Insert(2,11),(11,6) into R. Which additional tuples enter V?
Question 17(b)(ii), GATE 2002: R(A,B)={(1,2),(2,3),(2,4),(4,5),(6,7),(6,8),(9,10)}. View V is SELECT R1.A,R2.B FROM R R1,R R2 WHERE R1.B=R2.A. Original17(b)(ii): Insert(2,11),(11,6) into R. Which additional tuples enter V?
Tap to enlarge
Answer & solution

Answer: Additional tuples: {(1,11),(2,6),(11,7),(11,8)}. (no official key was published)

Let ΔR={(2,11),(11,6)}. A newly created length-two path must use at least one new edge, so inspect R⋈ΔR, ΔR⋈R, and ΔR⋈ΔR. The existing edge 1→2 followed by 2→11 adds (1,11). The new edge 11→6 followed by existing 6→7 or 6→8 adds (11,7),(11,8). The two new edges together form 2→11→6 and add (2,6). These four tuples are the additions; the original three remain. Longer paths such as 1→2→11→6 do not qualify, because this view joins exactly two copies of R rather than taking a transitive closure.

Original paper, page 9

Descriptive
Report issue

Query above-average examinees

SQL & Queries

Question 21(b), GATE 2001: examinee(regno,name,score), where regno is a primary key and score is real. List registration numbers with score above the relation-wide average.
Question 21(b), GATE 2001: examinee(regno,name,score), where regno is a primary key and score is real. List registration numbers with score above the relation-wide average.
Tap to enlarge
Answer & solution

Answer: SELECT regno FROM examinee WHERE score > (SELECT AVG(score) FROM examinee); (no official key was published)

Use an uncorrelated scalar subquery to compute one average over all examinees:

SELECT e.regno
FROM examinee AS e
WHERE e.score > (SELECT AVG(x.score) FROM examinee AS x);

The outer query compares each score with the same global average. Strict > excludes scores exactly equal to that average. No GROUP BY is needed because the intended comparison is to the whole relation, not a separate average per person or centre. The primary key ensures no duplicate registration number in the result. In SQL, AVG ignores NULL scores and comparison with NULL is unknown, so NULL-score rows do not qualify; the stated mathematical real-number model normally excludes this extra case.

Original paper, page 10

Descriptive
Report issue

List centres with a high scorer

SQL & Queries

Question 21(c), GATE 2001: examinee(regno,name,score) and appears(regno,centr_code). List centre codes having an examinee whose score exceeds 80.
Question 21(c), GATE 2001: examinee(regno,name,score) and appears(regno,centr_code). List centre codes having an examinee whose score exceeds 80.
Tap to enlarge
Answer & solution

Answer: SELECT DISTINCT a.centr_code FROM appears a JOIN examinee e ON e.regno=a.regno WHERE e.score>80; (no official key was published)

Join each appearance to its examinee using the shared registration number, keep scores strictly greater than 80, then project distinct centre codes:

SELECT DISTINCT a.centr_code
FROM appears AS a
JOIN examinee AS e ON e.regno = a.regno
WHERE e.score > 80;

DISTINCT is important because several high-scoring examinees can share a centre. This is an existential requirement: one qualifying examinee is sufficient. It is not a condition on centre average, and it does not require every examinee at that centre to exceed 80. An equivalent SQL formulation selects DISTINCT centre codes from appears a WHERE EXISTS (SELECT 1 FROM examinee e WHERE e.regno=a.regno AND e.score>80).

Original paper, page 10

2 marks · MCQ
Report issue

Projection of a Cartesian product in SQL

SQL & Queries

Question 2.25, GATE 2000: For r(w,x) and s(y,z), when is SELECT DISTINCT w,x FROM r,s guaranteed equal to r? Options: r duplicate-free and s nonempty; both duplicate-free; s duplicate-free and r nonempty; equal tuple counts.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step 1: FROM r,s creates a Cartesian product. If s is nonempty, every row of r appears at least once in that product; projection onto w,x and DISTINCT then returns exactly the distinct rows of r.

Step 2: To preserve SQL bag multiplicities as well, r itself must have no duplicates. No duplicate restriction on s is needed because DISTINCT removes replication.

Hence A. If s is empty, the result is empty even for nonempty r. If r has duplicates, DISTINCT changes it. The other listed conditions do not rule out these failures.

Original paper, page 6

2 marks · MCQ
Report issue

Replacing SQL unknown comparisons with false

SQL & Queries

Question 2.26, GATE 2000: Suppose every comparison involving NULL returns FALSE rather than UNKNOWN. Which pair ceases to be equivalent: x=5 versus NOT NOT(x=5); x=5 versus x>4 AND x<6 for integer x; x≠5 versus NOT(x=5); or none?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step 1: For an ordinary nonnull x, inequality x≠5 agrees with negated equality. But at x=NULL, the stipulated direct comparison x≠5 is FALSE, while x=5 is FALSE and its negation is TRUE. Thus C differs.

Step 2: Double negation still restores the original Boolean value, so A remains equivalent. In B, both comparisons on NULL are FALSE, making the conjunction FALSE just like equality; for nonnull integers the open interval(4,6) contains only 5.

Therefore only C among these pairs exposes the inconsistency. Standard SQL uses UNKNOWN precisely to avoid treating a negated unknown comparison as true.

Original paper, page 6

Descriptive
Report issue

Define transaction-prefix SQL view

SQL & Queries

Question 22(a), GATE 2000: Bank relation transaction(transno,acctno,date,amount) stores positive deposits and negative withdrawals. TP must contain (acctno,T1.date,T2.amount) for every pair of transactions on the same account with T2.date<=T1.date. Define TP in SQL.
Question 22(a), GATE 2000: Bank relation transaction(transno,acctno,date,amount) stores positive deposits and negative withdrawals. TP must contain (acctno,T1.date,T2.amount) for every pair of transactions on the same account with T2.date<=T1.date. Define TP in SQL.
Tap to enlarge
Answer & solution

Answer: Self-join by equal account and T2.date<=T1.date, without DISTINCT. (no official key was published)

One SQL definition is

CREATE VIEW TP (acctno, txn_date, amount) AS
SELECT T1.acctno, T1.date, T2.amount
FROM transaction AS T1
JOIN transaction AS T2
  ON T1.acctno = T2.acctno
 AND T2.date <= T1.date;

Here T1 chooses a balance-observation date and T2 chooses one transaction contributing to that balance. Include equality so the transaction on the observation date contributes; using < would produce the balance before, rather than after, that transaction and omit the first date’s self-pair. Each qualifying transaction pair contributes a row. Do not add DISTINCT: SQL’s bag semantics deliberately preserve separate same-amount transactions even though the projected triples may be identical. For example two deposits of 100 on different days generate two copies of (account,later_date,100), both of which must be summed. transaction and date can be reserved identifiers in some SQL dialects; quote the existing identifiers with that dialect’s supported delimiters if needed.

Original paper, page 10

Descriptive
Report issue

Find minimum historical account balances

SQL & Queries

Question 22(b), GATE 2000: Bank relation transaction(transno,acctno,date,amount) stores positive deposits and negative withdrawals. TP must contain (acctno,T1.date,T2.amount) for every pair of transactions on the same account with T2.date<=T1.date. Using only TP, create intermediate view V and query each account’s minimum balance after a transaction, excluding the initial zero. At most one transaction per account per day; each account has at least one transaction.
Question 22(b), GATE 2000: Bank relation transaction(transno,acctno,date,amount) stores positive deposits and negative withdrawals. TP must contain (acctno,T1.date,T2.amount) for every pair of transactions on the same account with T2.date<=T1.date. Using only TP, create intermediate view V and query each account’s minimum balance after a transaction, excluding the initial zero. At most one transaction per account per day; each account has at least one transaction.
Question 22(b), GATE 2000: Bank relation transaction(transno,acctno,date,amount) stores positive deposits and negative withdrawals. TP must contain (acctno,T1.date,T2.amount) for every pair of transactions on the same account with T2.date<=T1.date. Using only TP, create intermediate view V and query each account’s minimum balance after a transaction, excluding the initial zero. At most one transaction per account per day; each account has at least one transaction.
Tap to enlarge
Answer & solution

Answer: V sums amounts by account and observation date; final query takes MIN(balance) by account. (no official key was published)

Use two aggregation levels:
CREATE VIEW V (acctno, txn_date, balance) AS
SELECT acctno, txn_date, SUM(amount)
FROM TP
GROUP BY acctno, txn_date;

SELECT acctno, MIN(balance) AS minbalance
FROM V
GROUP BY acctno;
For a fixed account and T1 date, TP has one amount row for every transaction up to and including that date. SUM therefore gives the cumulative balance immediately after the transaction, assuming the opening balance is zero as specified. The one-transaction-per-account-per-day condition ensures each observation date has one T1 row, avoiding repeated copies of the entire prefix caused by multiple T1 transactions on the same day. Taking MIN over these cumulative balances returns the lowest post-transaction balance, including negative balances when appropriate. There is no row for account creation, so the initial zero is not accidentally included; a positive-only account correctly returns its first positive balance rather than zero. An account with amounts 100,100,−250 has balances 100,200,−50 and minimum−50. DISTINCT in TP would collapse the two 100 entries at the later dates and corrupt these sums. Distinct dates, not distinct amounts, define observation groups. Non-null numeric amounts and a comparable chronological date type are implicit in the bank model.

Original paper, page 10

2 marks · MSQ
Report issue

SQL myths

SQL & Queries

Question 2.25, GATE 1999: Which is correct: queries automatically remove duplicates; queries require indexes; column names may repeat within the same relation; none?
Tap to enlarge
Select all that apply
Answer & solution

Answer: D under the base-table reading (no official key was published)

Ordinary SELECT uses bag semantics; DISTINCT is needed when duplicate elimination is desired, so A is false. Indexes improve access paths but table scans execute queries without them, so B is false. A base table schema requires distinct column names within that table, so C is false in the stated relation-schema sense. Hence D. Different tables may share names and qualified references disambiguate them; some query result displays may also contain repeated labels, which is not the same as a valid base relation definition.

Original paper, page 6

2 marks · Descriptive
Report issue

Query high-paid Calcutta employees

SQL & Queries

Question 22(a), GATE 1999: EMP(Employee-no, Dept-no, Employee-name, Salary), DEPT(Dept-no, Dept-name, Location). Return employee names whose department is located at Calcutta and salary exceeds Rs.50,000.
Question 22(a), GATE 1999: EMP(Employee-no, Dept-no, Employee-name, Salary), DEPT(Dept-no, Dept-name, Location). Return employee names whose department is located at Calcutta and salary exceeds Rs.50,000.
Tap to enlarge
Answer & solution

Answer: Join EMP to DEPT and filter Location=Calcutta and Salary>50000. (no official key was published)

Use the common department identifier to join each employee to their department, then apply both predicates:

SELECT e."Employee-name"
FROM EMP AS e
JOIN DEPT AS d ON d."Dept-no" = e."Dept-no"
WHERE d.Location = 'Calcutta'
  AND e.Salary > 50000;

The double quotes are standard SQL identifier quoting, required here because the printed attribute names contain hyphens. A database schema using Employee_name and Dept_no may use those unquoted names instead. The inequality is strict: salary exactly 50000 does not qualify. The department join is essential because Location belongs to DEPT, not EMP. This returns one row per matching employee under the usual department-key assumption; two employees sharing a name may produce duplicate name values. Add DISTINCT only if the intended output is a set of distinct names rather than names per employee. SQL NULL salaries do not pass the comparison.

Original paper, page 9

3 marks · Descriptive
Report issue

Count high-paid staff in every department

SQL & Queries

Question 22(b), GATE 1999: EMP(Employee-no, Dept-no, Employee-name, Salary), DEPT(Dept-no, Dept-name, Location). For each department number, count employees whose salary exceeds Rs.1,00,000.
Question 22(b), GATE 1999: EMP(Employee-no, Dept-no, Employee-name, Salary), DEPT(Dept-no, Dept-name, Location). For each department number, count employees whose salary exceeds Rs.1,00,000.
Tap to enlarge
Answer & solution

Answer: LEFT JOIN all departments to qualifying employees and count the matching employee department values, including zeros. (no official key was published)

To interpret “for each department” literally, start from DEPT so that departments with zero qualifying employees are retained:

SELECT d."Dept-no", COUNT(e."Dept-no") AS high_salary_count
FROM DEPT AS d
LEFT JOIN EMP AS e
  ON e."Dept-no" = d."Dept-no"
 AND e.Salary > 100000
GROUP BY d."Dept-no";

The salary condition belongs in ON: placing it in WHERE would discard the null-extended rows and remove zero-count departments. COUNT(e."Dept-no") counts only actual matches, since a matched equality implies a non-null employee department value; COUNT(*) would incorrectly count the null-extended row as one. Salaries equal to 100000 do not qualify. This assumes the conventional unique department number in DEPT.
If the expected interpretation asks only for department numbers represented by qualifying employees, the shorter traditional query is:
SELECT "Dept-no", COUNT(*) AS high_salary_count
FROM EMP
WHERE Salary > 100000
GROUP BY "Dept-no";
That version omits zero-count departments. It is a different coverage choice, so the all-department query is preferable for the literal wording. Attribute names are quoted to preserve the printed hyphens.

Original paper, page 9

Descriptive
Report issue

Students liking a served ice cream

SQL & Queries

Question 7(a), GATE 1998: Given FREQUENTS(student,parlor), SERVES(parlor,ice_cream), and LIKES(student,ice_cream), print students who frequent at least one parlor serving at least one ice cream they like. Each student likes an ice cream and frequents a parlor.
Question 7(a), GATE 1998: Given FREQUENTS(student,parlor), SERVES(parlor,ice_cream), and LIKES(student,ice_cream), print students who frequent at least one parlor serving at least one ice cream they like. Each student likes an ice cream and frequents a parlor.
Question 7(a), GATE 1998: Given FREQUENTS(student,parlor), SERVES(parlor,ice_cream), and LIKES(student,ice_cream), print students who frequent at least one parlor serving at least one ice cream they like. Each student likes an ice cream and frequents a parlor.
Tap to enlarge
Answer & solution

Answer: Join FREQUENTS to SERVES by parlor and LIKES by both student and ice cream; select distinct students. (no official key was published)

A qualifying student needs one witness consisting of a frequented parlor and a flavor both served there and liked by that same student. Match those three facts with a join:

SELECT DISTINCT f.student
FROM FREQUENTS AS f
JOIN SERVES AS s
  ON s.parlor = f.parlor
JOIN LIKES AS l
  ON l.student = f.student
 AND l.ice_cream = s.ice_cream;

The schema spells the attribute as “ice-cream”; ice_cream above is a SQL-friendly identifier for that same field. If the actual schema uses a hyphen, use the database's identifier quoting, for example l."ice-cream" in standard SQL. The query assumes the ordinary relational model with non-NULL identifying values.

The first join enumerates flavors served at every parlor a student frequents. The second retains only flavors liked by that student. Both equalities in the second join matter: omitting the student equality would incorrectly let somebody else's preference qualify the student. DISTINCT prints each qualifying student once even if several parlors or flavors witness qualification.

For example, if Ada frequents P, P serves vanilla, and Ada likes vanilla, the triple survives. If Bob also frequents P but only likes chocolate, Bob does not survive unless P serves chocolate as well. The request is existential, so it needs neither relational division nor a test that every frequented parlor serves every liked flavor. The assumptions that students have some likes and visits do not by themselves imply qualification.

Original paper, page 6

Descriptive
Report issue

SQL grouped aggregation

SQL & Queries

Question 13(b), GATE 1994: COURSES(cno,cname), primary key cno; STUDENTS(rollno,sname,age,year), primary key rollno; REGISTERED_FOR(cno,rollno), composite primary key (cno,rollno). year denotes the student’s current year of study. Write SQL to print the age and year of the youngest student in each year.
Question 13(b), GATE 1994: COURSES(cno,cname), primary key cno; STUDENTS(rollno,sname,age,year), primary key rollno; REGISTERED_FOR(cno,rollno), composite primary key (cno,rollno). year denotes the student’s current year of study. Write SQL to print the age and year of the youngest student in each year.
Tap to enlarge
Answer & solution

Answer: SELECT MIN(age) AS age, year FROM STUDENTS GROUP BY year; (no official key was published)

1. Group rows by year so each year is processed independently.

2. MIN(age) computes the youngest age within that group. Output just age and year, as requested, rather than an arbitrary student name or roll number.

3. Ties need no extra rows because the requested attributes are identical for tied youngest students. Standard SQL ignores NULL ages; if all ages in a year are NULL, the result is NULL.

Original paper, page 6

5 marks · Descriptive
Report issue

Students taught by Ramesh

SQL & Queries

Question 23, GATE 1993: STUDENTS(rollno key,sname,saddr), COURSES(cno key,cname), ENROLL(rollno,cno composite key,grade), TEACH(tno,cno composite key,tname). FDs: rollno→sname,saddr; cno→cname; tno→tname; rollno,cno→grade. The reproduced cao/sdaddr spellings are interpreted as cno/saddr. Retrieve roll number and name of students with grade A in at least one course taught by a teacher named Ramesh.
Question 23, GATE 1993: STUDENTS(rollno key,sname,saddr), COURSES(cno key,cname), ENROLL(rollno,cno composite key,grade), TEACH(tno,cno composite key,tname). FDs: rollno→sname,saddr; cno→cname; tno→tname; rollno,cno→grade. The reproduced cao/sdaddr spellings are interpreted as cno/saddr. Retrieve roll number and name of students with grade A in at least one course taught by a teacher named Ramesh.
Question 23, GATE 1993: STUDENTS(rollno key,sname,saddr), COURSES(cno key,cname), ENROLL(rollno,cno composite key,grade), TEACH(tno,cno composite key,tname). FDs: rollno→sname,saddr; cno→cname; tno→tname; rollno,cno→grade. The reproduced cao/sdaddr spellings are interpreted as cno/saddr. Retrieve roll number and name of students with grade A in at least one course taught by a teacher named Ramesh.
Tap to enlarge
Answer & solution

Answer: Use EXISTS to correlate enrollment and teaching to each student. (no official key was published)

A student qualifies if some enrollment has their roll number and grade A, and some teaching row for that enrollment's course has tname='Ramesh'. The course number is the join between ENROLL and TEACH; names need not be unique teacher identifiers.

SELECT s.rollno, s.sname
FROM STUDENTS AS s
WHERE EXISTS (
  SELECT 1 FROM ENROLL AS e
  JOIN TEACH AS t ON t.cno=e.cno
  WHERE e.rollno=s.rollno
    AND e.grade='A' AND t.tname='Ramesh'
);

EXISTS yields one truth value for each outer student, so several qualifying courses or several teachers named Ramesh do not duplicate the output. A plain join version would need DISTINCT for that purpose. The COURSES relation is unnecessary because the query does not request a course name or another condition on it. No requirement says the student must have an A in every Ramesh-taught course; replacing EXISTS with universal division would answer a stronger question.

The source TEACH attribute is printed cao but described as course number cno, and its FD list prints sdaddr for saddr. These obvious naming inconsistencies are explicitly normalized in the query rather than treated as extra attributes.

Original paper, page 14

Report issue

Parts supplied within Delhi

SQL & Queries

Question 12(a.i), GATE 1991: SUPPLIER(SCODE,SNAME,CITY), PART(PCODE,PNAME,PDESC,CITY), PROJECTS(PRCODE,PRNAME,CITY), SPPR(SCODE,PCODE,PRCODE,QTY). SPPR records shipments of parts by suppliers to projects. Write SQL returning part codes supplied to a Delhi project by a Delhi supplier.
Question 12(a.i), GATE 1991: SUPPLIER(SCODE,SNAME,CITY), PART(PCODE,PNAME,PDESC,CITY), PROJECTS(PRCODE,PRNAME,CITY), SPPR(SCODE,PCODE,PRCODE,QTY). SPPR records shipments of parts by suppliers to projects. Write SQL returning part codes supplied to a Delhi project by a Delhi supplier.
Question 12(a.i), GATE 1991: SUPPLIER(SCODE,SNAME,CITY), PART(PCODE,PNAME,PDESC,CITY), PROJECTS(PRCODE,PRNAME,CITY), SPPR(SCODE,PCODE,PRCODE,QTY). SPPR records shipments of parts by suppliers to projects. Write SQL returning part codes supplied to a Delhi project by a Delhi supplier.
Tap to enlarge
Answer & solution

Answer: SELECT DISTINCT X.PCODE from the shipment/supplier/project join where both cities are DELHI. (no official key was published)

The shipment relation provides the association among a supplier, a part and a project. Join it to SUPPLIER on SCODE and to PROJECTS on PRCODE. The two city restrictions apply independently to supplier and project, not to PART.CITY.

SELECT DISTINCT X.PCODE
FROM SPPR AS X
JOIN SUPPLIER AS S ON S.SCODE = X.SCODE
JOIN PROJECTS AS P ON P.PRCODE = X.PRCODE
WHERE S.CITY = 'DELHI' AND P.CITY = 'DELHI';

A qualifying shipment is a witness that the part satisfies the request. DISTINCT ensures each code appears once even if multiple suppliers or projects witness it, or several shipment records exist. No join to PART is necessary because the requested code is already present in SPPR, under the usual foreign-key consistency assumption. If parts must also exist despite unenforced references, add JOIN PART AS T ON T.PCODE=X.PCODE. SQL string comparison follows the database's collation; DELHI is the source's city literal.

Original paper, page 7

Report issue

Intercity shipment triples

SQL & Queries

Question 12(a.ii), GATE 1991: SUPPLIER(SCODE,SNAME,CITY), PART(PCODE,PNAME,PDESC,CITY), PROJECTS(PRCODE,PRNAME,CITY), SPPR(SCODE,PCODE,PRCODE,QTY). SPPR records shipments of parts by suppliers to projects. Write SQL returning distinct triples (supplier city, part code, project city), excluding equal cities.
Question 12(a.ii), GATE 1991: SUPPLIER(SCODE,SNAME,CITY), PART(PCODE,PNAME,PDESC,CITY), PROJECTS(PRCODE,PRNAME,CITY), SPPR(SCODE,PCODE,PRCODE,QTY). SPPR records shipments of parts by suppliers to projects. Write SQL returning distinct triples (supplier city, part code, project city), excluding equal cities.
Question 12(a.ii), GATE 1991: SUPPLIER(SCODE,SNAME,CITY), PART(PCODE,PNAME,PDESC,CITY), PROJECTS(PRCODE,PRNAME,CITY), SPPR(SCODE,PCODE,PRCODE,QTY). SPPR records shipments of parts by suppliers to projects. Write SQL returning distinct triples (supplier city, part code, project city), excluding equal cities.
Tap to enlarge
Answer & solution

Answer: Join shipments to suppliers and projects, filter S.CITY <> P.CITY, and select the distinct three requested attributes. (no official key was published)

A row must describe an actual shipment rather than an arbitrary supplier/project combination. Use SPPR as the central relation and join the endpoint relations by their code keys. The supplier city is the first component; the destination project's city is the third.

SELECT DISTINCT S.CITY AS SUPPLIER_CITY,
                X.PCODE,
                P.CITY AS PROJECT_CITY
FROM SPPR AS X
JOIN SUPPLIER AS S ON S.SCODE = X.SCODE
JOIN PROJECTS AS P ON P.PRCODE = X.PRCODE
WHERE S.CITY <> P.CITY;

The predicate removes local shipments, and DISTINCT collapses repeated triples caused by different suppliers, projects or shipment rows. PART.CITY is irrelevant: it is neither endpoint requested in the result. Aliases make the two CITY columns distinguishable. Classical relational problems normally assume nonnull attributes. In SQL, if a city is NULL, the inequality is UNKNOWN and the row is excluded; a different policy for unknown cities would require an explicit requirement and predicate.

Original paper, page 7