How can I combine results from two SELECT queries with UNION?
Quick answer
Write the two SELECT queries with the same number of selected columns, then connect them with UNION to remove duplicate complete result rows or UNION ALL to retain them. For example, select the same item ID and name from current and archived tables. Duplicate checking applies to the complete selected rows, not just one column. [S1]
The question, the details, the next step.
A practical checklist
Write down the exact columns the combined result should contain.
Make each SELECT return the same number of columns.
Check that corresponding selected columns are in the intended order.
Use
UNIONfor distinct complete result rows orUNION ALLto retain repeats.Compare every selected value when checking why a row did or did not count as a duplicate.
A few more useful answers
Will UNION remove rows that share an item ID but have different names?
Not if both ID and name are selected: different complete result rows are not duplicates just because their IDs match. [S1] Choose selected columns that match the result you actually need.
Can the two SELECT statements return different numbers of columns?
No. Each constituent SELECT in a compound SELECT must return the same number of result columns. [S1]
Which operator keeps every row from both queries?
UNION ALL returns rows from both sides and retains duplicates. [S1]
Sources
References used for this guide.
- [S1] SQLite SELECT: compound SELECT and UNION operators sqlite.org · Checked
