PostgreSQL UNION

The UNION operator combines result sets of two or more SELECT statements into a single result set, removing duplicate rows by default.

Key Topics

1. Basic Syntax

SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;

Both queries must return the same number of columns with compatible data types.

2. UNION vs. UNION ALL

UNION ALL includes duplicate rows instead of removing them:

SELECT column1
FROM table1
UNION ALL
SELECT column1
FROM table2;

Best Practices

  • Use UNION ALL when you need duplicates for aggregation or specific logic.
  • Ensure columns align with compatible data types for each SELECT statement.

Key Takeaways

  • UNION merges multiple query results, removing duplicates by default.
  • UNION ALL retains all rows, including duplicates.