🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to PostgreSQL Notes
Topic #36

PostgreSQL UNION


UNION

The UNION operator is used to combine the result-set of two or more queries.

The queries in the union must follow these rules:

  • They must have the same number of columns
  • The columns must have the same data types
  • The columns must be in the same order

Example

        SELECT
        product_id, product_name
FROM products
UNION
SELECT
        testproduct_id, product_name
FROM testproducts
ORDER BY product_id;

UNION vs UNION ALL

With the UNION operator, if some rows in the two queries returns the exact same result, only one row will be listed, because UNION selects only distinct values.

Use UNION ALL to return duplicate values.

Let's make some changes to the queries, so that we have duplicate values in the result:

Example - UNION

        SELECT
        product_id
FROM products
UNION
SELECT
        testproduct_id
FROM testproducts
ORDER BY product_id;

Example - UNION ALL

        SELECT
        product_id
FROM products
UNION ALL
SELECT
        testproduct_id
FROM testproducts
ORDER BY product_id;

Want to go beyond the notes?

Join CodingNow 2.0's PostgreSQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

PostgreSQL UNION – FAQs

Quick answers about learning PostgreSQL UNION in PostgreSQL.

This free note from CodingNow 2.0 explains PostgreSQL UNION in PostgreSQL — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every PostgreSQL topic on CodingNow 2.0, including PostgreSQL UNION, is 100% free with no signup required.
With focused practice, most students grasp PostgreSQL UNION in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now