NIMCET, GATE, CUET & CBSE test series are live — start practicing free
syllabuzAI

SQL GROUP BY, HAVING and Nested Queries | GATE CSE

Learn SQL execution order, aggregates and NULLs, GROUP BY and HAVING, correlated subqueries, and IN, ANY, ALL and EXISTS for GATE CSE DBMS, with traced examples.

7 min read

AS

Aman Singh

Updated 26 November 2026

On this page

Quick answer: You write a SQL query as SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY, but it is evaluated in the order FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY. SELECT-FROM-WHERE matches the relational algebra expression π(σ(R₁ × … × Rₙ)), except that SQL keeps duplicates unless you add DISTINCT. WHERE filters rows and HAVING filters groups. In nested queries, IN means = ANY, NOT IN means <> ALL, and EXISTS checks whether the subquery returns any row. Aggregates other than COUNT(*) ignore NULLs.

GATE SQL questions usually give a small table and ask for the output, or ask which queries are equivalent. This topic is part of the Relational Algebra and SQL chapter.

Basic query and its relational algebra meaning

SQL
SELECT DISTINCT A1, A2
FROM R1, R2
WHERE P;

The equivalent relational algebra expression is:

πA1,A2(σP(R1×R2))\pi_{A_1, A_2}(\sigma_P(R_1 \times R_2))

SQL clauseRelational algebra operator
SELECTProjection π (duplicates kept unless DISTINCT)
FROMCross product ×
WHERESelection σ

Written order vs execution order

StepClauseWhat it does
1FROMBuilds the cross product or joins
2WHEREFilters rows
3GROUP BYForms groups
4HAVINGFilters groups
5SELECTComputes output columns
6DISTINCTRemoves duplicate rows
7ORDER BYSorts the result

Because SELECT runs after WHERE, you can't use a SELECT column alias inside WHERE.

Sample table used below

Emp(eid, dno, sal):

eiddnosal
110100
210200
320300
420300
530NULL

Aggregate functions and NULLs

  • COUNT(*) counts rows: 5.
  • COUNT(sal) counts non-null values: 4.
  • SUM(sal) = 900 and AVG(sal) = 900 / 4 = 225. The NULL is ignored, not treated as 0.
  • COUNT(DISTINCT sal) = 3 (100, 200 and 300).
  • A comparison with NULL gives UNKNOWN, and WHERE treats UNKNOWN as false.

GROUP BY

  • Rows with equal values in the grouping columns form one group, and each group gives one output row.
  • Every non-aggregated column in SELECT must appear in GROUP BY.

HAVING

  • HAVING filters groups after grouping. Its condition should use grouping columns or aggregate functions.
  • WHERE is tested on each row; HAVING is tested on each group.
SQL
SELECT dno, AVG(sal)
FROM Emp
GROUP BY dno
HAVING COUNT(*) > 1;

Step 1: Groups: 10 → {100, 200}, 20 → {300, 300}, 30 → {NULL}.

Step 2: Only groups with more than one row pass HAVING.

Output: (10, 150) and (20, 300).

In standard SQL, writing HAVING sal > 60 is an error, because sal is neither a grouping column nor inside an aggregate.

Nested queries

Non-correlated subquery

The inner query does not refer to the outer query, so it can be evaluated once, before the outer query.

Correlated subquery

The inner query refers to a table of the outer query, so it is evaluated again for each row of the outer query.

SQL
SELECT e.eid
FROM Emp e
WHERE e.sal > (SELECT AVG(f.sal)
               FROM Emp f
               WHERE f.dno = e.dno);

This finds employees who earn more than their own department's average. Dept 10's average is 150, so eid 2 qualifies. Dept 20's average is 300, so nobody there qualifies. Dept 30's average is NULL, so the comparison is UNKNOWN. Output: 2.

IN, ANY, ALL and EXISTS

ConstructMeaning
x IN (subquery)x equals some value returned
x op ANY (subquery)x op v is true for at least one v
x op ALL (subquery)x op v is true for every v (true if the subquery is empty)
EXISTS (subquery)The subquery returns at least one row

For single-column comparisons:

  • IN is the same as = ANY.
  • NOT IN is the same as <> ALL.
  • IN can express an equi-join, and ANY or EXISTS can express joins with other conditions.

Examples on Emp

SQL
SELECT eid FROM Emp
WHERE sal > ALL (SELECT sal FROM Emp WHERE dno = 10);

Salaries in dept 10 are 100 and 200, so we need sal > 200. Output: 3, 4. Row 5 has a NULL salary, so its comparison is UNKNOWN.

SQL
SELECT eid FROM Emp
WHERE sal > ANY (SELECT sal FROM Emp WHERE dno = 10);

Now we only need sal > 100. Output: 2, 3, 4.

Three ways to write the same query

Find women who earn more than some man, using Emp(eid, sal, gen):

SQL
-- Join
SELECT DISTINCT T1.eid
FROM Emp T1, Emp T2
WHERE T1.gen = 'F' AND T2.gen = 'M' AND T1.sal > T2.sal;

-- Nested with ANY
SELECT eid FROM Emp
WHERE gen = 'F'
  AND sal > ANY (SELECT sal FROM Emp WHERE gen = 'M');

-- Correlated with EXISTS
SELECT eid FROM Emp T1
WHERE T1.gen = 'F'
  AND EXISTS (SELECT * FROM Emp T2
              WHERE T2.gen = 'M' AND T1.sal > T2.sal);

The NOT IN and NULL trap

Watch out: if the subquery of NOT IN returns even one NULL, x NOT IN (…) can never be TRUE, so the outer query returns no rows. NOT EXISTS does not have this problem.

WITH clause (common table expressions)

WITH defines a named temporary result that you can reuse in the main query:

SQL
WITH DeptAvg (dno, avg_sal) AS
  (SELECT dno, AVG(sal) FROM Emp GROUP BY dno)
SELECT e.eid
FROM Emp e, DeptAvg d
WHERE e.dno = d.dno AND e.sal > d.avg_sal;

Set operations and joins

  • UNION, INTERSECT and EXCEPT remove duplicates. UNION ALL, INTERSECT ALL and EXCEPT ALL keep them. Both operands must be union compatible.
  • Explicit joins (INNER JOIN … ON, NATURAL JOIN, LEFT, RIGHT and FULL OUTER JOIN) mean the same as in relational algebra.

Summary table

RuleDetail
Execution orderFROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY
DuplicatesKept unless DISTINCT; UNION, INTERSECT and EXCEPT remove them
COUNT(*) vs COUNT(col)Rows vs non-null values
INSame as = ANY
NOT INSame as <> ALL; returns nothing if the subquery has a NULL
> ALL on an empty subqueryTRUE

Exam tips

  • Trace the query in execution order, writing the intermediate table after each step.
  • Before you compute any aggregate, cross out NULLs (except for COUNT(*)).
  • When two queries look equivalent, check NULLs, duplicates and empty subqueries. Those are where they usually differ.

Common mistakes

  • Expecting SQL to remove duplicates on its own. It doesn't without DISTINCT.
  • Putting aggregate conditions in WHERE instead of HAVING.
  • Treating NULL as 0 in AVG and SUM.
  • Using NOT IN when the subquery can return NULLs.
  • Forgetting that > ALL of an empty set is true.

Practice questions

Q1. On the sample table, what does SELECT COUNT(*), COUNT(sal) FROM Emp WHERE dno <> 10 return?

Answer: Rows with dno 20, 20 and 30 remain, so the result is (3, 2).

Q2. What does SELECT dno FROM Emp GROUP BY dno HAVING MAX(sal) = MIN(sal) return?

Answer: Dept 20 (300 = 300). Dept 10 fails. For dept 30, MAX and MIN are both NULL, and NULL = NULL is UNKNOWN, so it fails too. Output: 20.

Q3. Rewrite x IN (SELECT y FROM S) using EXISTS.

Answer: EXISTS (SELECT * FROM S WHERE S.y = x).

FAQs

What is the order of execution of a SQL query?

FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT and then ORDER BY.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping. HAVING filters whole groups after GROUP BY, usually with an aggregate such as COUNT or AVG.

What is the difference between a correlated and a non-correlated subquery?

A non-correlated subquery runs once on its own. A correlated subquery uses values from the outer query, so it runs again for each outer row.

Is IN the same as = ANY in SQL?

Yes, for single-column comparisons. NOT IN is likewise the same as <> ALL.

Why does NOT IN sometimes return no rows?

If the subquery returns a NULL, every NOT IN test becomes UNKNOWN or FALSE, so no outer row qualifies.

Conclusion

Trace each query in execution order on the given table and handle NULLs and duplicates carefully. That covers most GATE SQL questions. Go back to the Relational Algebra and SQL chapter, revise relational algebra, or compare with tuple relational calculus.

Concept Check

MEDIUM

Consider a relational database containing the following schemas.

Catalogue (primary key: sno, pno)

snopnocost
S1P1150
S1P250
S1P3100
S2P4200
S2P5250
S3P1250
S3P2150
S3P5300
S3P4250

Suppliers (primary key: sno)

snosnamelocation
S1M/s Royal furnitureDelhi
S2M/s Balaji furnitureBangalore
S3M/s Premium furnitureChennai

Parts (primary key: pno)

pnopnamepart_spec
P1TableWood
P2ChairWood
P3TableSteel
P4AlmirahSteel
P5AlmirahWood
SQL
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);

The number of rows returned by the above SQL query is

Suggested for you