Skip to main content

Databases (DBMS)

SQL

SQL questions in GATE are traces: work out exactly what a query returns on a small table. Know the logical order of evaluation, three-valued NULL logic, and what each aggregate and join does.

~5 hrs ~1.5–2 marks · Must-score 9 samples · 9 practice · 9 cards

GATE CSE SQL — SELECT basics, joins, aggregates, GROUP BY and HAVING, nested and correlated queries, EXISTS, IN/ANY/ALL, set operations, NULL semantics, DDL/DML and constraints, with traced examples, sample questions, flashcards and drills.

Learning outcomes

  • Trace the logical evaluation order FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY
  • Predict results of joins, outer joins, aggregates and GROUP BY/HAVING
  • Evaluate IN, NOT IN, EXISTS, ANY/ALL and correlated subqueries including NULL cases
  • Recall DDL/DML/DCL commands and constraint behaviour (PRIMARY KEY, UNIQUE, CHECK, FOREIGN KEY)

SELECT, joins and logical evaluation order

  • General form: SELECT [DISTINCT] columns FROM tables [JOIN ... ON ...] [WHERE condition] [GROUP BY cols] [HAVING condition] [ORDER BY cols]. SQL returns a MULTISET: duplicates remain unless DISTINCT is used.
  • LOGICAL ORDER of evaluation: FROM (joins) -> WHERE -> GROUP BY -> HAVING -> SELECT -> DISTINCT -> ORDER BY. So WHERE cannot use aggregates or select-list aliases; HAVING can use aggregates.
  • JOINS: INNER JOIN keeps matches only; LEFT/RIGHT/FULL OUTER JOIN keep unmatched rows padded with NULL; CROSS JOIN (or comma) gives the Cartesian product; NATURAL JOIN joins on equal-named columns; a SELF JOIN uses aliases to compare rows of the same table.
  • Row counts: if the join column has value v occurring m times in R and n times in S, the inner join produces m * n rows for v. Left outer join adds the unmatched left rows once each.
  • SET OPERATIONS: UNION, INTERSECT and EXCEPT remove duplicates; UNION ALL / INTERSECT ALL / EXCEPT ALL keep multiplicities. Operands must have compatible columns.
  • Pattern matching: LIKE with % (any string) and _ (one character). BETWEEN a AND b is inclusive. ORDER BY ... ASC/DESC sorts the final result.
  • Aliases (AS) rename columns/tables. A column alias defined in SELECT cannot be used in WHERE.
  • MULTISET RULES for set operators on bags: if a value occurs m times in R and n times in S, then UNION ALL gives m + n copies, INTERSECT ALL gives min(m, n), EXCEPT ALL gives max(m - n, 0). The plain UNION / INTERSECT / EXCEPT give 1 copy (or 0) because they eliminate duplicates.
  • A WHERE condition on the NULL-padded side of an OUTER JOIN (for example WHERE S.c = 5 after a LEFT JOIN) discards the padded rows and turns the query into an inner join. Put such conditions in the ON clause to keep outer-join semantics.
  • NATURAL JOIN uses ALL equal-named columns, JOIN ... USING (col) uses only the listed columns, and JOIN ... ON can use any condition. Two tables with no equal-named column make NATURAL JOIN equal to a CROSS JOIN, which is a common GATE trap.
  • Rows returned by SELECT from a Cartesian product of several tables = product of the row counts; each extra table multiplies the size. A WHERE equality between key and foreign key then keeps only the matching combinations.
ClauseRuns onCan use aggregates?
WHEREindividual rows (before grouping)no
GROUP BYforms groups from remaining rowsn/a
HAVINGgroups (after grouping)yes
SELECTbuilds output columns per group/rowyes
ORDER BYfinal resultyes (and aliases)

Worked example

Problem. R(a) = {1, 2, 2, 3} and S(a) = {2, 2, 3, 4}. How many rows are in R INNER JOIN S ON R.a = S.a and in R LEFT OUTER JOIN S ON R.a = S.a?

Solution. Value 2: 2 * 2 = 4 rows; value 3: 1 * 1 = 1 row; so the inner join has 5 rows. The R tuple with value 1 has no match and appears once with NULL: left outer join = 5 + 1 = 6 rows.

Four Venn diagrams for inner, left outer, right outer and full outer join of R(a) = 1,2,2,3 and S(a) = 2,2,3,4 giving 5, 6, 6 and 7 rows, with row-count rules.
Join row counts: inner = sum of m * n per matching value; each outer join adds the unmatched rows of its preserved side (R: 1 row, S: 1 row), so full outer = 5 + 1 + 1 = 7.

Set operators on bags: worked row counts

  • GATE asks the NUMBER OF ROWS returned. First write each table as a bag (list of values with multiplicity), then apply the operator formula per distinct value.
  • UNION removes duplicates after combining; UNION ALL is just concatenation, so its row count is always |R| + |S|. INTERSECT ALL and EXCEPT ALL use min and subtraction of the multiplicities.
  • EXCEPT is NOT commutative: R EXCEPT S and S EXCEPT R differ. UNION and INTERSECT are commutative and associative; their ALL versions also commute (counts add or take the minimum).
  • Set operators treat NULLs as equal to each other (a NULL in R and a NULL in S count as the same value), unlike the = comparison in WHERE.
Operator on bagsCopies of a value (m in R, n in S)Example with R = {1,2,2,3}, S = {2,2,3,4}
UNION1{1, 2, 3, 4} (4 rows)
UNION ALLm + n8 rows
INTERSECT1 if both m, n > 0{2, 3} (2 rows)
INTERSECT ALLmin(m, n){2, 2, 3} (3 rows)
EXCEPT (R - S)1 if m > 0 and n = 0{1} (1 row)
EXCEPT ALL (R - S)max(m - n, 0){1} (1 row)

Worked example

Problem. R(a) = {1, 1, 2, 3, 3, 3} and S(a) = {1, 3, 3, 4}. Find the number of rows returned by R UNION S, R UNION ALL S, R INTERSECT ALL S and R EXCEPT ALL S.

Solution. Distinct values: 1, 2, 3, 4. UNION = 4 rows {1, 2, 3, 4}. UNION ALL = 6 + 4 = 10 rows. INTERSECT ALL: value 1 gives min(2, 1) = 1, value 3 gives min(3, 2) = 2, value 2 and 4 give 0, so 3 rows. EXCEPT ALL (R - S): value 1 gives max(2 - 1, 0) = 1, value 2 gives 1, value 3 gives max(3 - 2, 0) = 1, so 3 rows.

Aggregates, GROUP BY, HAVING and NULL semantics

  • Aggregates: COUNT(*), COUNT(col), COUNT(DISTINCT col), SUM, AVG, MIN, MAX. COUNT(*) counts all rows; COUNT(col) counts non-NULL values; SUM/AVG/MIN/MAX IGNORE NULLs; on an empty input COUNT gives 0 but SUM/AVG/MIN/MAX give NULL.
  • GROUP BY forms one group per distinct combination of the grouping columns; rows with NULL in a grouping column are placed in ONE group together. Every non-aggregated column in SELECT must appear in GROUP BY.
  • HAVING filters groups; WHERE filters rows first. A query with aggregates and no GROUP BY treats the whole table as one group and returns exactly one row.
  • THREE-VALUED LOGIC: comparison with NULL yields UNKNOWN (NULL = NULL is UNKNOWN, not TRUE). WHERE/HAVING keep only rows where the condition is TRUE. Use IS NULL / IS NOT NULL. TRUE AND UNKNOWN = UNKNOWN, FALSE AND UNKNOWN = FALSE, TRUE OR UNKNOWN = TRUE, NOT UNKNOWN = UNKNOWN.
  • DISTINCT, GROUP BY and UNION treat NULLs as equal (one NULL value). Arithmetic with NULL gives NULL.
  • NOT IN with a NULL in the subquery list returns NO rows (x NOT IN (1, NULL) is never TRUE). NOT EXISTS does not suffer from this problem.
  • ORDER BY places NULLs first or last depending on the system; GATE questions usually avoid this.

Formulas to remember

  • COUNT(*) >= COUNT(col) = number of non-NULL values
  • AVG(col) = SUM(col) / COUNT(col) (NULLs ignored)
  • x IN (a, b, NULL) = (x=a) OR (x=b) OR UNKNOWN
Expression on Emp(sal) = 10, 20, 30, NULL, 50ValueWhy
COUNT(*)5counts every row
COUNT(sal)4NULL ignored
SUM(sal)11010+20+30+50
AVG(sal)27.5110 / 4, not 110 / 5
MAX(sal), MIN(sal)50, 10NULL ignored
COUNT(*) where sal > 1000empty input: COUNT is 0
SUM(sal) where sal > 100NULLempty input: SUM is NULL

Worked example

Problem. Emp(eid, dept, sal) = (1,A,10), (2,A,20), (3,B,30), (4,B,NULL), (5,NULL,50). Evaluate SELECT dept, COUNT(*), COUNT(sal), AVG(sal) FROM Emp GROUP BY dept.

Solution. Group A: COUNT(*) = 2, COUNT(sal) = 2, AVG = 15. Group B: 2, 1 (one NULL salary), AVG = 30. The NULL dept forms its own group: 1, 1, AVG = 50. Three result rows.

Logical evaluation order FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY with a trace of Emp rows grouped by dept, showing averages 15, 30 and 50 and which groups pass HAVING AVG greater than 20.
Trace of GROUP BY dept HAVING AVG(sal) > 20: group A (avg 15) fails, group B (avg 30) and the NULL-dept group (avg 50) pass. NULL grouping values form one group.

Nested queries, EXISTS, DDL/DML and constraints

  • A SUBQUERY can appear in WHERE (IN, NOT IN, EXISTS, NOT EXISTS, comparison with ANY/ALL/SOME), in FROM (derived table) or in SELECT (scalar subquery). A scalar subquery must return at most one row and one column.
  • x IN (subquery) is x = ANY (subquery); x NOT IN (subquery) is x <> ALL (subquery). x > ALL (subquery) means greater than the maximum; x > ANY (subquery) means greater than the minimum. For an empty subquery ALL is TRUE and ANY is FALSE.
  • CORRELATED subquery references a column of the outer query, so it is re-evaluated for each outer row. EXISTS (subquery) is TRUE if the subquery returns at least one row (independent of NULL values); NOT EXISTS gives "no matching row" and implements division: students for whom NOT EXISTS a course for which NOT EXISTS an enrolment.
  • Second-highest salary: SELECT MAX(sal) FROM Emp WHERE sal < (SELECT MAX(sal) FROM Emp). N-th highest uses a correlated COUNT(DISTINCT) or LIMIT/OFFSET.
  • DDL: CREATE, ALTER, DROP, TRUNCATE (removes all rows, keeps structure). DML: INSERT, UPDATE, DELETE, SELECT. DCL: GRANT, REVOKE. TCL: COMMIT, ROLLBACK, SAVEPOINT. DELETE removes selected rows (can be rolled back), TRUNCATE removes all rows quickly, DROP removes the table.
  • CONSTRAINTS: PRIMARY KEY (UNIQUE + NOT NULL), UNIQUE (duplicates not allowed; NULLs are allowed in most systems), NOT NULL, CHECK (condition; an UNKNOWN result is accepted), FOREIGN KEY ... REFERENCES ... ON DELETE/UPDATE actions, DEFAULT.
  • Views: CREATE VIEW v AS SELECT ...; a view definition is stored and re-evaluated. Indexes are created with CREATE INDEX. A TRIGGER is an action executed automatically on INSERT/UPDATE/DELETE; an assertion/CHECK expresses integrity rules.
  • Embedded SQL/cursors: a cursor lets a host program fetch the rows of a query one at a time.
CommandRemovesRollback / structure
DELETEchosen rows (WHERE) or all rowscan be rolled back; table kept
TRUNCATEall rows quicklytable structure kept; usually cannot be rolled back
DROPthe whole table and its definitionstructure gone
UPDATEnothing; modifies valuescan be rolled back

Worked example

Problem. Using Emp from the previous example (salaries 10, 20, 30, NULL, 50), evaluate SELECT MAX(sal) FROM Emp WHERE sal < (SELECT MAX(sal) FROM Emp).

Solution. Inner query: MAX(sal) = 50 (NULL ignored). Outer: rows with sal < 50 are 10, 20, 30 (the NULL row gives UNKNOWN and is dropped). MAX of those = 30, the second-highest salary.

Truth tables for AND, OR and NOT with TRUE, FALSE and UNKNOWN, and a trace showing why x NOT IN (1, NULL) never returns TRUE.
Three-valued logic: a comparison with NULL is UNKNOWN and WHERE keeps only TRUE rows, which is why NOT IN with a NULL in the list returns no rows.

Worked SQL queries: correlated subqueries, division and top-N

  • CORRELATED COUNT pattern: "employees earning more than the average of their own department": SELECT e.eid FROM Emp e WHERE e.sal > (SELECT AVG(sal) FROM Emp WHERE dept = e.dept). The subquery is re-evaluated per outer row (or per distinct dept by an optimiser).
  • N-th HIGHEST salary: SELECT DISTINCT e1.sal FROM Emp e1 WHERE (SELECT COUNT(DISTINCT e2.sal) FROM Emp e2 WHERE e2.sal > e1.sal) = n - 1. For n = 1 the count is 0, so e1.sal is the maximum.
  • DIVISION with NOT EXISTS: students who took ALL courses = SELECT s.sid FROM Student s WHERE NOT EXISTS (SELECT * FROM Course c WHERE NOT EXISTS (SELECT * FROM Enrolled e WHERE e.sid = s.sid AND e.cid = c.cid)). The outer NOT EXISTS looks for a course the student missed.
  • DIVISION with COUNT: SELECT sid FROM Enrolled GROUP BY sid HAVING COUNT(DISTINCT cid) = (SELECT COUNT(*) FROM Course). It is correct only when every enrolled cid exists in Course (referential integrity) and no duplicates are counted twice.
  • DUPLICATE ELIMINATION traps: SELECT dept FROM Emp returns one row per employee; SELECT DISTINCT dept returns one row per distinct dept (with NULL counted once). COUNT(DISTINCT col) ignores NULLs.
  • IN versus EXISTS: x IN (subquery) compares one value with a list and is affected by NULLs when negated; EXISTS only checks for at least one row. NOT IN and NOT EXISTS give different answers when the subquery produces NULLs.
  • COMPARING with ALL / ANY: x > ALL (empty set) is TRUE, so a query using > ALL on a department with no employees returns every row; x > ANY (empty set) is FALSE.

Worked example

Problem. Student(sid) = {1, 2, 3}, Course(cid) = {c1, c2}, Enrolled(sid, cid) = {(1,c1), (1,c2), (2,c1), (3,c2), (3,c1)}. How many rows does the NOT EXISTS division query for "students enrolled in all courses" return? Which sids?

Solution. Student 1 took c1 and c2: no missed course, so NOT EXISTS (missed course) is TRUE. Student 2 took only c1 and missed c2, so the inner subquery returns a course and the outer NOT EXISTS is FALSE. Student 3 took c2 and c1: qualifies. The query returns 2 rows: sids 1 and 3. The COUNT version agrees: COUNT(DISTINCT cid) is 2 for sids 1 and 3 and 1 for sid 2, with COUNT(*) FROM Course = 2.

Exam tips

  • Always evaluate in order: FROM, WHERE, GROUP BY, HAVING, SELECT. WHERE cannot contain aggregates.
  • COUNT(*) counts NULL rows; COUNT(col) and all other aggregates ignore NULLs.
  • x NOT IN (list with NULL) never returns TRUE; remember to check subquery results for NULL.
  • Inner join rows for a value = (count in R) * (count in S); add the unmatched rows for outer joins.
  • NOT EXISTS inside NOT EXISTS is the SQL way to express relational division.
Exam pattern · 9 questions

GATE sample questions & answers

9 GATE-style MCQs for SQL with full explanations. Attempt each question before revealing the answer.

Q1 GATE NULL-aggregate pattern

Emp(eid, dept, sal) = (1,A,10), (2,A,20), (3,B,30), (4,B,NULL), (5,NULL,50). What are the values of COUNT(*) and COUNT(sal) over the whole table?

  • A) 5 and 5
  • B) 5 and 4
  • C) 4 and 4
  • D) 4 and 5
Show answer & explanation

Answer: B

COUNT(*) counts all 5 rows; COUNT(sal) ignores the single NULL salary: 4.

Q2

For the same Emp table, how many rows does SELECT dept FROM Emp GROUP BY dept HAVING AVG(sal) > 20 return?

  • A) 0
  • B) 1
  • C) 2
  • D) 3
Show answer & explanation

Answer: C

Averages: A = 15, B = 30 (NULL ignored), NULL group = 50. Groups B and NULL satisfy AVG > 20, so 2 rows (one with dept NULL).

Q3

T(x) = {1, 2, 3} and U(y) = {1, NULL}. How many rows does SELECT x FROM T WHERE x NOT IN (SELECT y FROM U) return?

  • A) 0
  • B) 1
  • C) 2
  • D) 3
Show answer & explanation

Answer: A

For x = 2: 2 <> 1 is TRUE but 2 <> NULL is UNKNOWN, so the AND is UNKNOWN and the row is rejected; x = 1 is FALSE; x = 3 behaves like x = 2. No row qualifies.

Q4

R(a) = {1, 2, 2, 3} and S(a) = {2, 2, 3, 4}. The number of rows in R INNER JOIN S ON R.a = S.a is:

  • A) 3
  • B) 4
  • C) 5
  • D) 6
Show answer & explanation

Answer: C

Value 2 gives 2 * 2 = 4 rows; value 3 gives 1 row; total 5.

Q5

With the same R and S as above, R LEFT OUTER JOIN S ON R.a = S.a returns how many rows?

  • A) 5
  • B) 6
  • C) 7
  • D) 8
Show answer & explanation

Answer: B

The 5 matches plus the single unmatched R row (a = 1) padded with NULL = 6.

Q6

Which statement about WHERE and HAVING is correct?

  • A) WHERE can contain aggregates but HAVING cannot
  • B) HAVING is evaluated before GROUP BY
  • C) WHERE filters rows before grouping; HAVING filters groups after grouping and may use aggregates
  • D) They are interchangeable in every query
Show answer & explanation

Answer: C

WHERE acts on individual rows prior to GROUP BY. HAVING works on the formed groups and can reference aggregate functions.

Q7

On Emp with salaries 10, 20, 30, NULL, 50, SELECT MAX(sal) FROM Emp WHERE sal < (SELECT MAX(sal) FROM Emp) returns:

  • A) 20
  • B) 30
  • C) 50
  • D) NULL
Show answer & explanation

Answer: B

The inner query returns 50; rows with sal < 50 are 10, 20, 30; their maximum is 30 (the second-highest salary).

Q8

R(x) = {1, 2, 2} and S(x) = {2, 3}. The number of rows returned by SELECT x FROM R UNION SELECT x FROM S and by the same query with UNION ALL are respectively:

  • A) 3 and 5
  • B) 5 and 3
  • C) 3 and 3
  • D) 5 and 5
Show answer & explanation

Answer: A

UNION removes duplicates giving {1, 2, 3} = 3 rows. UNION ALL keeps all rows: 3 + 2 = 5.

Q9

Which SQL query returns the employees who have NO department (dept is unknown)?

  • A) SELECT * FROM Emp WHERE dept = NULL
  • B) SELECT * FROM Emp WHERE dept IS NULL
  • C) SELECT * FROM Emp WHERE dept <> NULL
  • D) SELECT * FROM Emp WHERE dept = 0
Show answer & explanation

Answer: B

Comparisons with NULL are UNKNOWN, so = NULL and <> NULL never return rows. IS NULL is the correct test.

Topic drill · 9 questions

9 practice questions — SQL

Extra page-specific practice beyond the GATE samples. Attempt all 9, then reveal answers to check your reasoning.

P1

T(a) = {1, 1, 2, NULL, NULL}. What is the number of rows returned by SELECT DISTINCT a FROM T?

  • A) 2
  • B) 3
  • C) 4
  • D) 5
Show answer & explanation

Answer: B) 3

DISTINCT treats NULLs as equal: the distinct values are 1, 2 and NULL.

P2

SELECT COUNT(a) FROM T for T(a) = {1, 1, 2, NULL, NULL} returns:

  • A) 5
  • B) 3
  • C) 2
  • D) 0
Show answer & explanation

Answer: B) 3

COUNT(a) counts the non-NULL values: 1, 1, 2.

P3

SELECT SUM(sal) FROM Emp WHERE 1 = 0 returns:

  • A) 0
  • B) NULL
  • C) an error
  • D) no row
Show answer & explanation

Answer: B) NULL

An aggregate without GROUP BY always returns one row; SUM of an empty set is NULL (COUNT would be 0).

P4

Which of the following is TRUE about the value of the condition (NULL = NULL) in a WHERE clause?

  • A) TRUE
  • B) FALSE
  • C) UNKNOWN, so the row is not selected
  • D) causes an error
Show answer & explanation

Answer: C) UNKNOWN, so the row is not selected

Any comparison with NULL is UNKNOWN; WHERE keeps only rows where the condition is TRUE.

P5

Emp salaries are 10, 20, 30. SELECT eid FROM Emp WHERE sal > ALL (SELECT sal FROM Emp WHERE dept = 'X') where no employee is in dept X returns:

  • A) no rows
  • B) all employees
  • C) only the top earner
  • D) an error
Show answer & explanation

Answer: B) all employees

ALL over an empty set is TRUE for every outer row, so every employee qualifies.

P6

Which clause is used to filter groups produced by GROUP BY?

  • A) WHERE
  • B) HAVING
  • C) ORDER BY
  • D) DISTINCT
Show answer & explanation

Answer: B) HAVING

HAVING applies a condition to groups after aggregation.

P7

A table has a UNIQUE constraint on column c. Which insertion sequence is accepted by most systems?

  • A) c = 1, then c = 1
  • B) c = NULL, then c = NULL
  • C) c = 1, then c = 2, then c = 1
  • D) none of the above
Show answer & explanation

Answer: B) c = NULL, then c = NULL

UNIQUE rejects duplicate non-NULL values; multiple NULLs are allowed because NULL = NULL is not TRUE.

P8

Which command removes all rows of a table but keeps its structure?

  • A) DROP TABLE
  • B) TRUNCATE TABLE
  • C) ALTER TABLE
  • D) REMOVE TABLE
Show answer & explanation

Answer: B) TRUNCATE TABLE

TRUNCATE empties the table; DROP removes the table definition too.

P9

R has 4 rows and S has 3 rows; the query SELECT * FROM R, S (no WHERE clause) returns:

  • A) 7 rows
  • B) 12 rows
  • C) 3 rows
  • D) 4 rows
Show answer & explanation

Answer: B) 12 rows

Listing two tables without a join condition is a Cartesian product: 4 * 3 = 12 rows.

Topic FAQs

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping and cannot use aggregates; HAVING filters groups after GROUP BY and can use aggregate functions.

Why does NOT IN sometimes return no rows?

If the subquery returns a NULL, then x <> NULL is UNKNOWN, so the whole NOT IN condition can never be TRUE. Use NOT EXISTS or filter out NULLs.

Does COUNT(column) count NULLs?

No. COUNT(column) counts only non-NULL values, while COUNT(*) counts every row. SUM, AVG, MIN and MAX also ignore NULLs.

What is the difference between DELETE, TRUNCATE and DROP?

DELETE removes chosen rows and can be rolled back; TRUNCATE removes all rows but keeps the table; DROP removes the table definition itself.

Quick revision · 9 cards

9 flashcards — SQL

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 Logical evaluation order of a SELECT query?
Q2 COUNT(*) vs COUNT(col)?
Q3 What does x = NULL evaluate to?
Q4 Why can NOT IN return nothing?
Q5 UNION vs UNION ALL?
Q6 x > ALL (subquery) means?
Q7 DELETE vs TRUNCATE vs DROP?
Q8 How is division written in SQL?
Q9 Rows produced by an inner join on value v?