sqlcmd.net validated sql reference
intermediate set-operations MySQL MariaDB SQL Server PostgreSQL SQLite

Combine Query Results With UNION

Merge result sets from two `SELECT` statements into one, removing duplicate rows by default.

Docker-validated Not currently validation-green

Merge active and archived product lists into one result

The four distinct product names from both tables are merged and sorted alphabetically. Because all names are unique across the two tables, UNION and UNION ALL would produce the same result here.

Rows loaded before the example query runs.
Setup
CREATE TABLE products (id INT, name VARCHAR(50));

CREATE TABLE archived_products (id INT, name VARCHAR(50));

INSERT INTO
  products (id, name)
VALUES
  (1, 'Keyboard'),
  (2, 'Mouse');

INSERT INTO
  archived_products (id, name)
VALUES
  (3, 'Trackball'),
  (4, 'Joystick');
Shared across supported engines.
SQL
SELECT
  name
FROM
  products
UNION
SELECT
  name
FROM
  archived_products
ORDER BY
  name;
Returned rows for the shared example.
name
Joystick
Keyboard
Mouse
Trackball

Output is identical across all engines.

Where this command helps.

  • combining rows from parallel tables with the same shape
  • stitching together multiple query branches into one output

What the command is doing.

UNION appends the rows of a second query to the first and deduplicates the combined result. Both queries must return the same number of columns with compatible types. Use UNION ALL to skip deduplication and keep every row, which is faster when duplicates are not a concern.