Home / Learn Secure SQL / UNION and UNION ALL

UNION and UNION ALL

Combining results from two queries.

Quick summaryCombining results from two queries.

How to think about this

Stacking resultsfirst SELECTUNION / UNION ALLsecond SELECT (samecolumn count)combined rows
Stacking results

The basic idea

UNION stacks the results of two SELECT statements with the same number of columns into one result set; UNION ALL does the same but keeps duplicate rows.

Why this comes up

It is a normal, useful SQL feature for combining data from different sources — and also the exact mechanism attackers misuse when a query is built unsafely, which is why the "Why hand-built SQL is risky" part of this course revisits it.

The mechanics

Match the column count and compatible types on both sides; use UNION ALL unless you specifically need duplicates removed.

Where it is used

  • Web application code review
  • Backend development
  • Database administration
A legitimate UNIONSQL: edit and run

Two different sources combined into one labelled list, with matching column counts and compatible types.

Quick check

1. UNION requires the two SELECTs to...