Do the tables have to have the same number of columns when combining them?

Question

In the context of this exercise, do tables have to have the same number of columns when combining them?

Answer

Yes, when combining two tables using a UNION, they must have the same number of columns. The columns do not need to have the same name, because they are combined based on column positions rather than the column names. However, they should have similar data types.

9 Likes

I just managed to get in to this stage of the course.

Regarding the answer to this question as tables must have the same amount of columns, I tired WITH statement to create temporary tables with the columns I want to select. Then I just used UNION to merge them both.

Basically, if tables do not have the same amount of columns and you want to use UNION you can first create temporary tables with WITH statement to select the amount of columns you want. I hope this helps!.

WITH songs_test AS (
SELECT id, title, year
FROM songs
),
bonus_songs_test AS (
SELECT id, title, year
FROM bonus_songs
)
SELECT *
FROM songs_test
UNION
SELECT *
FROM bonus_songs_test
LIMIT 10;