SQL QuestSQL Interview Questions › Subqueries & CTEs

UNION ALL Dedup: Cross-Dataset Search

MediumFreeQuerying BasicsSubqueries & CTEsConditional LogicAggregation & Grouping

Combine employee and customer data into a single contact list. Using UNION ALL, create a result with name, source ('employee' or 'customer'), and detail (department for employees, membership for customers). Then wrap it in a CTE and count how many contacts exist per source. The final output has TWO columns — source and contact_count — with three rows: one per source, plus a summary ROW labeled 'total' (source = 'total', contact_count = sum of all contacts). Place the 'total' row last; order the other rows alphabetically by source. This tests UNION ALL vs UNION semantics, which matters when datasets may overlap.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".

Schema

customers

customer_idnameemailsignup_datemembershiptotal_orders
1John Smithjohn.smith@email.com2023-01-15Gold15
2Emma Wilsonemma.wilson@email.com2023-03-20Silver8
3Michael Brownmichael.brown@email.com2023-02-10Gold12

Expected output: employee: 50, customer: 16, total: 66 (or less if UNION deduplicates)

Hint

CTE: SELECT name, 'employee' AS source, department AS detail FROM employees UNION ALL SELECT name, 'customer', membership FROM customers. SQLite has no GROUP BY ROLLUP — build the 'total' row with a second UNION ALL over the CTE, then sort it last with ORDER BY CASE source WHEN 'total' THEN 1 ELSE 0 END, source.

Concepts

SELECT UNION ALL UNION CTE CASE GROUP BY UNION / Set Operations

Practise the topic: SQL practice questions · CTE practice · CASE WHEN practice · GROUP BY exercises

In these company practice sets

Databricks · Plaid · Snowflake

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

Department Roster with GROUP_CONCATMedium · FreeConsistent Director AnalysisMedium · FreeBelow Department AverageMedium · FreeHighest Total Salary Budget DepartmentMedium · FreeFare Imputation AnalysisMedium · FreeAbove-Average Departments (Derived Table)Medium · Free

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test