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;

11 Likes

What do I do if I want to limit table1 (songs table in this case) and display all of the rows of table2 (bonus_songs table in this case)?

I am asking this because when I use LIMIT after doing the UNION, I do not know if the bonus_songs rows have been added. I don’t want to display the entire table and scroll all the way down to see if the UNION has taken place.

That’s really Nice. Thankyou @khanster321 for sharing such Great Information.