Chapter 4

SQL revision patterns

SQL counting questions are best solved one logical stage at a time. Track rows, nulls and duplicates separately. The examples below use portable query patterns and do not depend on a particular query optimiser.

4.1 Bags, joins and logical evaluation order

Past papers · CS 2014–2026 (23 papers): 5 questions, 8 marks · DA 2024–2026 (3 papers): 1 question, 1 mark

The logical order is FROM/joins and ON, WHERE, GROUP BY, HAVING, output expressions, DISTINCT, ORDER BY, then row limiting. This is a reasoning order, not a promise about physical execution. SELECT names output expressions and behaves like bag projection; WHERE corresponds to selection.

UNION, INTERSECT, EXCEPT remove duplicates by default. Their ALL forms use, respectively, multiplicity a+ba+b, min⁡(a,b)\min(a,b) and max⁡(0,a−b)\max(0,a-b) for a tuple with input multiplicities a,ba,b. A comma in FROM makes a cross product unless a condition connects the tables. NATURAL JOIN equates every common column; JOIN ... USING(k) equates only the named columns.

4.2 NULL and three-valued logic

A comparison with NULL, including NULL = NULL, is UNKNOWN. Use IS NULL or IS NOT NULL. WHERE, HAVING and ON retain only TRUE; a CHECK constraint rejects FALSE but accepts UNKNOWN. NOT NULL is therefore a separate constraint.

ppqqpp AND qqpp OR qq
TRUEUNKNOWNUNKNOWNTRUE
FALSEUNKNOWNFALSEUNKNOWN
UNKNOWNUNKNOWNUNKNOWNUNKNOWN

NOT UNKNOWN is UNKNOWN. COUNT(*) counts rows; COUNT(x) counts non-null values; COUNT(DISTINCT x) counts distinct non-null values. SUM, AVG, MIN, MAX ignore null arguments. For no non-null arguments, they return NULL; the corresponding counts return zero. GROUP BY puts null grouping values together. DISTINCT also collapses duplicate null-containing rows.

4.3 Grouping, aggregation and derived tables

Past papers · CS 2014–2026 (23 papers): 4 questions, 7 marks · DA 2024–2026 (3 papers): 1 question, 2 marks

WHERE removes input rows; HAVING removes groups. Grouping by name merges different entities with the same name; grouping by a unique identifier does not. For portable exam SQL, every selected nonaggregate expression must be grouped; recognise any explicit functional-dependency relaxation stated by the DBMS.

An aggregate query without GROUP BY creates one group even on empty input. A query grouped by an ordinary column has no groups on empty input. A scalar subquery must return at most one row: no row gives null, while multiple rows are an error. WITH names a query result for reuse; a derived table is a parenthesised query in FROM.

To attach a group size to each original row, aggregate the group key and count in a derived table, then join back on that group key. Grouping by the row's primary key instead usually gives count one. For a per-group maximum, compare both group key and maximum value; retain all tied maxima.

WITH totals AS (
  SELECT shop, SUM(amount) AS total
  FROM Sale
  GROUP BY shop
)
SELECT shop
FROM totals
WHERE total > (SELECT AVG(total) FROM totals);

4.4 Subqueries, ANY, ALL and universal SQL

Past papers · CS 2014–2026 (23 papers): 8 questions, 14 marks · DA 2024–2026 (3 papers): 2 questions, 3 marks

EXISTS is TRUE if a subquery returns any row, even a row whose values are null. IN is equality with ANY; NOT IN is inequality with ALL. A correlated subquery uses the current outer row; an uncorrelated aggregate computes a value over its own input, not automatically over the outer row's group.

Predicate, non-null xx and nonempty null-free set SSEquivalent test
x>ANY⁡(S)x>\operatorname{ANY}(S)x>min⁡(S)x>\min(S)
x>ALL⁡(S)x>\operatorname{ALL}(S)x>max⁡(S)x>\max(S)
x<ANY⁡(S)x<\operatorname{ANY}(S)x<max⁡(S)x<\max(S)
x<ALL⁡(S)x<\operatorname{ALL}(S)x<min⁡(S)x<\min(S)

On an empty set, ANY is FALSE and ALL is TRUE, regardless of the comparison operator. With null comparisons, ANY is TRUE if any comparison is TRUE, FALSE if all are FALSE, otherwise UNKNOWN. ALL is FALSE if any comparison is FALSE, TRUE if all are TRUE, otherwise UNKNOWN. The empty-set identities still apply.

The pattern below finds candidates covering every required item. Keys cid and iid are non-null. Duplicate matching pairs do not affect existence.

SELECT C.cid
FROM Candidate AS C
WHERE NOT EXISTS (
  SELECT 1 FROM Required AS R
  WHERE NOT EXISTS (
    SELECT 1 FROM HasItem AS H
    WHERE H.cid = C.cid AND H.iid = R.iid
  )
);

This includes all candidates if Required is empty. To require at least one associated item as well, add that separate existence condition. NOT EXISTS(required EXCEPT possessed) is another set-based universal pattern when schemas match.

4.5 Data definitions, updates and constraint checks

CREATE TABLE Centre (
  centre_id INTEGER PRIMARY KEY,
  label VARCHAR(40) NOT NULL
);
CREATE TABLE Member (
  member_id INTEGER PRIMARY KEY,
  centre_id INTEGER REFERENCES Centre(centre_id),
  credits INTEGER CHECK (credits >= 0)
);

INSERT adds rows, UPDATE changes selected rows and DELETE removes selected rows. Omitting WHERE affects all rows. ALTER TABLE changes a definition. CREATE VIEW defines a named query; a join/aggregate view is not automatically updatable.

A row CHECK is not a general replacement for referential actions or cross-table integrity. A theoretical database-wide assertion can express a cross-table condition, but that does not by itself reproduce CASCADE actions. SQL implementations differ in assertion support. In exam questions, separate a declarative condition from the actions that maintain it.

Last-minute recall

  • Count joined rows before grouping or deduplication.
  • WHERE filters rows; HAVING filters groups.
  • COUNT(*) and COUNT(column) differ when nulls occur.
  • A missing join predicate can create a large cross product.
  • ALL(empty) is TRUE; ANY(empty) is FALSE.
  • EXISTS does not multiply an outer row by its number of matches.
  • Average subgroup means using subgroup counts, unless equal weighting is explicitly intended.
  • A row CHECK accepts UNKNOWN; it does not imply NOT NULL.

Revise offline: the whole Databases and Data Warehousing handbook as one PDF

58 pages · 2.7 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections