Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageJuniorCommonTheory

What is the difference between UNION and UNION ALL, and how would you test either result?

Answer

UNION combines compatible result sets and removes duplicate rows, while UNION ALL keeps every row and normally avoids the duplicate-removal work. Both sides must return compatible column counts and types, but column names and ordering still need deliberate handling. Tests should include duplicates within and across inputs, NULL values, empty inputs, type conversions, ordering applied only at the final result and reconciliation of expected row counts.

Strong answer includes

  • distinguishes duplicate removal from retention
  • mentions compatible result shapes
  • tests nulls, empty inputs and row-count reconciliation

Practical example

See duplicate removal versus retention
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

UNION performs duplicate elimination across the combined result. UNION ALL preserves multiplicity and is usually cheaper when duplicate removal is not part of the requirement.

Expected result: UNION may return fewer rows than UNION ALL when the inputs overlap.

#sql#union#duplicates#query-results

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery