sql union vs join code example

Example 1: difference between join vs union

JOIN combines the ROWs, we will have longer rows at the end. 
We are joining the rows from two or more related tables.

UNION combines the COLUMNs, we will have longer columns at the end.
UNION combine two different query.
We are joining the columns from two or more related tables.
Can be non related tables but queries must select same column names
with same data type.

Example 2: UNION ALL LEFT JOIN

SELECT
    comments.*, users.company, users.contact_person, users.email
    FROM
        comments
    LEFT JOIN users ON users.user_id = comments.user_id
    WHERE
        comment_id = %s
UNION ALL
SELECT activity.*, users.company, users.contact_person, users.email
    FROM
        activity
    LEFT JOIN users ON users.user_id = activity.user_id
    WHERE
        comment_id = %s
ORDER BY
    timestamp ASC

Example 3: join vs union

JOIN combines the ROWs, we will have longer rows at the end. 
We are joining the rows from two or more related tables.

UNION combines the COLUMNs, we will have longer columns at the end.
UNION combine two different query.
We are joining the columns from two or more related tables.
Can be non related tables but queries must select same
column names with same data type.

Tags:

Sql Example