A union query is a database query that combines the rows returned by two or more SELECT statements into one result set. The statements must return the same number of columns with compatible data types, and UNION removes duplicate rows unless UNION ALL is used.
How Union Queries Work
A union query is a set-based database construct, so its behaviour depends on the database engine, the shape of each SELECT list, and whether the query uses duplicate-eliminating UNION or duplicate-preserving UNION ALL. Because it combines result sets rather than joining tables horizontally, it is best understood as a way to stack compatible records into one output stream.
The core requirement is structural compatibility. Each SELECT must return the same number of columns, and corresponding columns need compatible data types or coercible values. When that alignment is wrong, the query fails before the database can combine the rows, which makes union queries as much about schema shape as about result content.
Why Union Queries Matter in Database Design
Union queries are useful when data lives in parallel tables, when reports need a consolidated view across similar entities, or when an application must merge rows from different sources that share the same logical structure. They are common in reporting, data migration, and compatibility layers where normalising everything into one table is not practical.
They also make semantic assumptions visible. A union only works cleanly when the meaning of each column is aligned across all SELECT statements, so the query design forces the author to think carefully about labels, ordering, data types, and null handling. In practice, that often exposes modelling gaps or inconsistent field conventions early.
UNION Versus UNION ALL
The most important behavioural difference is duplicate handling. UNION removes duplicate rows from the combined result, while UNION ALL keeps every row returned by each SELECT. That makes UNION safer when a single deduplicated list is required, but it can be more expensive because the database must compare rows and eliminate repeats.
UNION ALL is usually the better choice when duplicates are meaningful, when performance matters, or when the caller will handle deduplication later. UNION is the better choice when the result set is meant to represent distinct values or unique logical records. Choosing between them is therefore both a correctness decision and a performance decision.
Common Failure Modes and Query Considerations
Union queries fail most often because the SELECT statements are not truly compatible. A mismatch in column count, incompatible types, inconsistent ordering, or an aliasing mistake can produce confusing results or runtime errors. Even when the query executes, a poorly designed union can hide data-quality problems by merging semantically different fields into one output.
Performance can also become a practical concern on large datasets, especially when UNION must sort or deduplicate many rows. The safest approach is to treat the union as a precise contract between result sets: align columns intentionally, prefer explicit casts when needed, and verify whether the query should preserve or suppress duplicates before it reaches production.
Risk and Threat Considerations
Union queries are sometimes used in injection payloads because they can expose data from additional tables or views when an application concatenates unsanitised input into SQL. The risk is not the union operator itself, but the way it can be abused to reshape a query and surface unintended rows.
Failure mechanism: An attacker discovers how many columns the original query returns, matches the column layout, and uses UNION-based injection to merge attacker-controlled output with legitimate query results. If the application leaks raw database errors or reflects query output, that path can reveal sensitive data.
Impact: Compromised queries can disclose records, credentials, tokens, or other sensitive application data, and may also help an attacker enumerate schema details for follow-on exploitation.
Standards & Framework Alignment
This section maps relevant standards and security frameworks to the operational risks and controls described in this guidance.
OWASP API Security Top 10 addresses the attack and risk surface, while OWASP ASVS, NIST SP 800-53 Rev 5 and CIS Controls v8 set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| OWASP ASVS | V4 — API and Web Service Security | Union query misuse often appears in SQL access paths exposed through web requests. |
| Recommendation — Validate database-facing request handling so untrusted input cannot reshape SQL queries. | ||
| NIST SP 800-53 Rev 5 | SI-10 — Information Input Validation | Union-query abuse depends on accepting attacker-controlled input into SQL statement structure. |
| AC-3 — Access Enforcement | Union queries can expose data beyond the intended row set when authorization is weak. | |
| Recommendation — Validate and constrain input before it can alter database query syntax. Enforce access rules so query paths cannot return data outside the user’s entitlement. | ||
| OWASP API Security Top 10 | API1 — Broken Object Level Authorization | Union-based query abuse can expose objects or rows the caller should not access. |
| Recommendation — Check object-level authorization on every data access path before returning rows. | ||
| CIS Controls v8 | CIS-16 — Application Software Security | SQL construction flaws in applications are a classic software-security weakness affecting union queries. |
| Recommendation — Review application query construction to prevent SQL injection and data exposure. | ||
Practitioner Guidance
Why practitioners should care: Treat union queries as a correctness and exposure boundary, not just a syntax feature. The same structural properties that make them useful for reporting also make them dangerous when query text is influenced by untrusted input.
Common misunderstanding: Developers sometimes assume that UNION is harmless because it only combines result sets. In reality, any place where user input can alter the SELECT structure deserves the same care as other SQL construction points, especially where result data is returned to an application or browser.
Practitioner takeaway: Use parameterised queries, restrict dynamic SQL construction, and review any union-based query that reaches externally influenced input for both correctness and data exposure risk.
Related resources from NHI Mgmt Group
Deepen Your Knowledge
Free weekly newsletter
Subscribe to the NHI & AI Identity Journal
The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.
Bonus 33% off our NHI Course when you subscribe.
Reviewed and updated by the NHIMG editorial team on November 25, 2026.
NHI Mgmt Group — the #1 independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org