Ask Your Question
3

How can tables with differing columns be combined together through union?

asked 2023-05-14 02:13:26 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-14 02:21:01 +0000

lakamha gravatar image

To combine tables with differing columns through union, the columns from both tables must be made compatible. This can be done by adding NULL values or default values for missing columns in one table so that they match the columns in the other table.

For example, suppose we have two tables:

Table 1: - Name - Age

Table 2: - Name - Gender - Occupation

To combine these tables, we can add a default value for Occupation in Table 1, so that the number of columns in both tables match:

SELECT Name, Age, NULL AS Gender, 'unemployed' AS Occupation FROM Table 1 UNION SELECT Name, NULL AS Age, Gender, Occupation FROM Table 2

This will create a new table with all the columns from both tables, and default values for missing columns as needed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-14 02:13:26 +0000

Seen: 14 times

Last updated: May 14 '23